oauth2.go 12 KB

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