oauth2.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package oauth2 provides support for making
  5. // OAuth2 authorized and authenticated HTTP requests.
  6. // It can additionally grant authorization with Bearer JWT.
  7. package oauth2 // import "golang.org/x/oauth2"
  8. import (
  9. "bytes"
  10. "errors"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "sync"
  15. "golang.org/x/net/context"
  16. "golang.org/x/oauth2/internal"
  17. )
  18. // NoContext is the default context you should supply if not using
  19. // your own context.Context (see https://golang.org/x/net/context).
  20. //
  21. // Deprecated: Use context.Background() or context.TODO() instead.
  22. var NoContext = context.TODO()
  23. // RegisterBrokenAuthHeaderProvider registers an OAuth2 server
  24. // identified by the tokenURL prefix as an OAuth2 implementation
  25. // which doesn't support the HTTP Basic authentication
  26. // scheme to authenticate with the authorization server.
  27. // Once a server is registered, credentials (client_id and client_secret)
  28. // will be passed as query parameters rather than being present
  29. // in the Authorization header.
  30. // See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
  31. func RegisterBrokenAuthHeaderProvider(tokenURL string) {
  32. internal.RegisterBrokenAuthHeaderProvider(tokenURL)
  33. }
  34. // Config describes a typical 3-legged OAuth2 flow, with both the
  35. // client application information and the server's endpoint URLs.
  36. // For the client credentials 2-legged OAuth2 flow, see the clientcredentials
  37. // package (https://golang.org/x/oauth2/clientcredentials).
  38. type Config struct {
  39. // ClientID is the application's ID.
  40. ClientID string
  41. // ClientSecret is the application's secret.
  42. ClientSecret string
  43. // Endpoint contains the resource server's token endpoint
  44. // URLs. These are constants specific to each server and are
  45. // often available via site-specific packages, such as
  46. // google.Endpoint or github.Endpoint.
  47. Endpoint Endpoint
  48. // RedirectURL is the URL to redirect users going through
  49. // the OAuth flow, after the resource owner's URLs.
  50. RedirectURL string
  51. // Scope specifies optional requested permissions.
  52. Scopes []string
  53. }
  54. // A TokenSource is anything that can return a token.
  55. type TokenSource interface {
  56. // Token returns a token or an error.
  57. // Token must be safe for concurrent use by multiple goroutines.
  58. // The returned Token must not be modified.
  59. Token() (*Token, error)
  60. }
  61. // Endpoint contains the OAuth 2.0 provider's authorization and token
  62. // endpoint URLs.
  63. type Endpoint struct {
  64. AuthURL string
  65. TokenURL string
  66. }
  67. var (
  68. // AccessTypeOnline and AccessTypeOffline are options passed
  69. // to the Options.AuthCodeURL method. They modify the
  70. // "access_type" field that gets sent in the URL returned by
  71. // AuthCodeURL.
  72. //
  73. // Online is the default if neither is specified. If your
  74. // application needs to refresh access tokens when the user
  75. // is not present at the browser, then use offline. This will
  76. // result in your application obtaining a refresh token the
  77. // first time your application exchanges an authorization
  78. // code for a user.
  79. AccessTypeOnline AuthCodeOption = SetAuthURLParam("access_type", "online")
  80. AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline")
  81. // ApprovalForce forces the users to view the consent dialog
  82. // and confirm the permissions request at the URL returned
  83. // from AuthCodeURL, even if they've already done so.
  84. ApprovalForce AuthCodeOption = SetAuthURLParam("approval_prompt", "force")
  85. )
  86. // An AuthCodeOption is passed to Config.AuthCodeURL.
  87. type AuthCodeOption interface {
  88. setValue(url.Values)
  89. }
  90. type setParam struct{ k, v string }
  91. func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) }
  92. // SetAuthURLParam builds an AuthCodeOption which passes key/value parameters
  93. // to a provider's authorization endpoint.
  94. func SetAuthURLParam(key, value string) AuthCodeOption {
  95. return setParam{key, value}
  96. }
  97. // AuthCodeURL returns a URL to OAuth 2.0 provider's consent page
  98. // that asks for permissions for the required scopes explicitly.
  99. //
  100. // State is a token to protect the user from CSRF attacks. You must
  101. // always provide a non-zero string and validate that it matches the
  102. // the state query parameter on your redirect callback.
  103. // See http://tools.ietf.org/html/rfc6749#section-10.12 for more info.
  104. //
  105. // Opts may include AccessTypeOnline or AccessTypeOffline, as well
  106. // as ApprovalForce.
  107. func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string {
  108. var buf bytes.Buffer
  109. buf.WriteString(c.Endpoint.AuthURL)
  110. v := url.Values{
  111. "response_type": {"code"},
  112. "client_id": {c.ClientID},
  113. "redirect_uri": internal.CondVal(c.RedirectURL),
  114. "scope": internal.CondVal(strings.Join(c.Scopes, " ")),
  115. "state": internal.CondVal(state),
  116. }
  117. for _, opt := range opts {
  118. opt.setValue(v)
  119. }
  120. if strings.Contains(c.Endpoint.AuthURL, "?") {
  121. buf.WriteByte('&')
  122. } else {
  123. buf.WriteByte('?')
  124. }
  125. buf.WriteString(v.Encode())
  126. return buf.String()
  127. }
  128. // PasswordCredentialsToken converts a resource owner username and password
  129. // pair into a token.
  130. //
  131. // Per the RFC, this grant type should only be used "when there is a high
  132. // degree of trust between the resource owner and the client (e.g., the client
  133. // is part of the device operating system or a highly privileged application),
  134. // and when other authorization grant types are not available."
  135. // See https://tools.ietf.org/html/rfc6749#section-4.3 for more info.
  136. //
  137. // The HTTP client to use is derived from the context.
  138. // If nil, http.DefaultClient is used.
  139. func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) {
  140. return retrieveToken(ctx, c, url.Values{
  141. "grant_type": {"password"},
  142. "username": {username},
  143. "password": {password},
  144. "scope": internal.CondVal(strings.Join(c.Scopes, " ")),
  145. })
  146. }
  147. // Exchange converts an authorization code into a token.
  148. //
  149. // It is used after a resource provider redirects the user back
  150. // to the Redirect URI (the URL obtained from AuthCodeURL).
  151. //
  152. // The HTTP client to use is derived from the context.
  153. // If a client is not provided via the context, http.DefaultClient is used.
  154. //
  155. // The code will be in the *http.Request.FormValue("code"). Before
  156. // calling Exchange, be sure to validate FormValue("state").
  157. func (c *Config) Exchange(ctx context.Context, code string) (*Token, error) {
  158. return retrieveToken(ctx, c, url.Values{
  159. "grant_type": {"authorization_code"},
  160. "code": {code},
  161. "redirect_uri": internal.CondVal(c.RedirectURL),
  162. })
  163. }
  164. // Client returns an HTTP client using the provided token.
  165. // The token will auto-refresh as necessary. The underlying
  166. // HTTP transport will be obtained using the provided context.
  167. // The returned client and its Transport should not be modified.
  168. func (c *Config) Client(ctx context.Context, t *Token) *http.Client {
  169. return NewClient(ctx, c.TokenSource(ctx, t))
  170. }
  171. // TokenSource returns a TokenSource that returns t until t expires,
  172. // automatically refreshing it as necessary using the provided context.
  173. //
  174. // Most users will use Config.Client instead.
  175. func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource {
  176. tkr := &tokenRefresher{
  177. ctx: ctx,
  178. conf: c,
  179. }
  180. if t != nil {
  181. tkr.refreshToken = t.RefreshToken
  182. }
  183. return &reuseTokenSource{
  184. t: t,
  185. new: tkr,
  186. }
  187. }
  188. // tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token"
  189. // HTTP requests to renew a token using a RefreshToken.
  190. type tokenRefresher struct {
  191. ctx context.Context // used to get HTTP requests
  192. conf *Config
  193. refreshToken string
  194. }
  195. // WARNING: Token is not safe for concurrent access, as it
  196. // updates the tokenRefresher's refreshToken field.
  197. // Within this package, it is used by reuseTokenSource which
  198. // synchronizes calls to this method with its own mutex.
  199. func (tf *tokenRefresher) Token() (*Token, error) {
  200. if tf.refreshToken == "" {
  201. return nil, errors.New("oauth2: token expired and refresh token is not set")
  202. }
  203. tk, err := retrieveToken(tf.ctx, tf.conf, url.Values{
  204. "grant_type": {"refresh_token"},
  205. "refresh_token": {tf.refreshToken},
  206. })
  207. if err != nil {
  208. return nil, err
  209. }
  210. if tf.refreshToken != tk.RefreshToken {
  211. tf.refreshToken = tk.RefreshToken
  212. }
  213. return tk, err
  214. }
  215. // reuseTokenSource is a TokenSource that holds a single token in memory
  216. // and validates its expiry before each call to retrieve it with
  217. // Token. If it's expired, it will be auto-refreshed using the
  218. // new TokenSource.
  219. type reuseTokenSource struct {
  220. new TokenSource // called when t is expired.
  221. mu sync.Mutex // guards t
  222. t *Token
  223. }
  224. // Token returns the current token if it's still valid, else will
  225. // refresh the current token (using r.Context for HTTP client
  226. // information) and return the new one.
  227. func (s *reuseTokenSource) Token() (*Token, error) {
  228. s.mu.Lock()
  229. defer s.mu.Unlock()
  230. if s.t.Valid() {
  231. return s.t, nil
  232. }
  233. t, err := s.new.Token()
  234. if err != nil {
  235. return nil, err
  236. }
  237. s.t = t
  238. return t, nil
  239. }
  240. // StaticTokenSource returns a TokenSource that always returns the same token.
  241. // Because the provided token t is never refreshed, StaticTokenSource is only
  242. // useful for tokens that never expire.
  243. func StaticTokenSource(t *Token) TokenSource {
  244. return staticTokenSource{t}
  245. }
  246. // staticTokenSource is a TokenSource that always returns the same Token.
  247. type staticTokenSource struct {
  248. t *Token
  249. }
  250. func (s staticTokenSource) Token() (*Token, error) {
  251. return s.t, nil
  252. }
  253. // HTTPClient is the context key to use with golang.org/x/net/context's
  254. // WithValue function to associate an *http.Client value with a context.
  255. var HTTPClient internal.ContextKey
  256. // NewClient creates an *http.Client from a Context and TokenSource.
  257. // The returned client is not valid beyond the lifetime of the context.
  258. //
  259. // As a special case, if src is nil, a non-OAuth2 client is returned
  260. // using the provided context. This exists to support related OAuth2
  261. // packages.
  262. func NewClient(ctx context.Context, src TokenSource) *http.Client {
  263. if src == nil {
  264. c, err := internal.ContextClient(ctx)
  265. if err != nil {
  266. return &http.Client{Transport: internal.ErrorTransport{Err: err}}
  267. }
  268. return c
  269. }
  270. return &http.Client{
  271. Transport: &Transport{
  272. Base: internal.ContextTransport(ctx),
  273. Source: ReuseTokenSource(nil, src),
  274. },
  275. }
  276. }
  277. // ReuseTokenSource returns a TokenSource which repeatedly returns the
  278. // same token as long as it's valid, starting with t.
  279. // When its cached token is invalid, a new token is obtained from src.
  280. //
  281. // ReuseTokenSource is typically used to reuse tokens from a cache
  282. // (such as a file on disk) between runs of a program, rather than
  283. // obtaining new tokens unnecessarily.
  284. //
  285. // The initial token t may be nil, in which case the TokenSource is
  286. // wrapped in a caching version if it isn't one already. This also
  287. // means it's always safe to wrap ReuseTokenSource around any other
  288. // TokenSource without adverse effects.
  289. func ReuseTokenSource(t *Token, src TokenSource) TokenSource {
  290. // Don't wrap a reuseTokenSource in itself. That would work,
  291. // but cause an unnecessary number of mutex operations.
  292. // Just build the equivalent one.
  293. if rt, ok := src.(*reuseTokenSource); ok {
  294. if t == nil {
  295. // Just use it directly.
  296. return rt
  297. }
  298. src = rt.new
  299. }
  300. return &reuseTokenSource{
  301. t: t,
  302. new: src,
  303. }
  304. }