oauth2.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. "errors"
  12. "net/http"
  13. "net/url"
  14. "strings"
  15. "sync"
  16. "golang.org/x/net/context"
  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 HTTP client to use is derived from the context.
  148. // If nil, http.DefaultClient is used.
  149. func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) {
  150. v := url.Values{
  151. "grant_type": {"password"},
  152. "username": {username},
  153. "password": {password},
  154. }
  155. if len(c.Scopes) > 0 {
  156. v.Set("scope", strings.Join(c.Scopes, " "))
  157. }
  158. return retrieveToken(ctx, c, v)
  159. }
  160. // Exchange converts an authorization code into a token.
  161. //
  162. // It is used after a resource provider redirects the user back
  163. // to the Redirect URI (the URL obtained from AuthCodeURL).
  164. //
  165. // The HTTP client to use is derived from the context.
  166. // If a client is not provided via the context, http.DefaultClient is used.
  167. //
  168. // The code will be in the *http.Request.FormValue("code"). Before
  169. // calling Exchange, be sure to validate FormValue("state").
  170. //
  171. // Opts may include the PKCE verifier code if previously used in AuthCodeURL.
  172. // See https://www.oauth.com/oauth2-servers/pkce/ for more info.
  173. func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error) {
  174. v := url.Values{
  175. "grant_type": {"authorization_code"},
  176. "code": {code},
  177. }
  178. if c.RedirectURL != "" {
  179. v.Set("redirect_uri", c.RedirectURL)
  180. }
  181. for _, opt := range opts {
  182. opt.setValue(v)
  183. }
  184. return retrieveToken(ctx, c, v)
  185. }
  186. // Client returns an HTTP client using the provided token.
  187. // The token will auto-refresh as necessary. The underlying
  188. // HTTP transport will be obtained using the provided context.
  189. // The returned client and its Transport should not be modified.
  190. func (c *Config) Client(ctx context.Context, t *Token) *http.Client {
  191. return NewClient(ctx, c.TokenSource(ctx, t))
  192. }
  193. // TokenSource returns a TokenSource that returns t until t expires,
  194. // automatically refreshing it as necessary using the provided context.
  195. //
  196. // Most users will use Config.Client instead.
  197. func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource {
  198. tkr := &tokenRefresher{
  199. ctx: ctx,
  200. conf: c,
  201. }
  202. if t != nil {
  203. tkr.refreshToken = t.RefreshToken
  204. }
  205. return &reuseTokenSource{
  206. t: t,
  207. new: tkr,
  208. }
  209. }
  210. // tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token"
  211. // HTTP requests to renew a token using a RefreshToken.
  212. type tokenRefresher struct {
  213. ctx context.Context // used to get HTTP requests
  214. conf *Config
  215. refreshToken string
  216. }
  217. // WARNING: Token is not safe for concurrent access, as it
  218. // updates the tokenRefresher's refreshToken field.
  219. // Within this package, it is used by reuseTokenSource which
  220. // synchronizes calls to this method with its own mutex.
  221. func (tf *tokenRefresher) Token() (*Token, error) {
  222. if tf.refreshToken == "" {
  223. return nil, errors.New("oauth2: token expired and refresh token is not set")
  224. }
  225. tk, err := retrieveToken(tf.ctx, tf.conf, url.Values{
  226. "grant_type": {"refresh_token"},
  227. "refresh_token": {tf.refreshToken},
  228. })
  229. if err != nil {
  230. return nil, err
  231. }
  232. if tf.refreshToken != tk.RefreshToken {
  233. tf.refreshToken = tk.RefreshToken
  234. }
  235. return tk, err
  236. }
  237. // reuseTokenSource is a TokenSource that holds a single token in memory
  238. // and validates its expiry before each call to retrieve it with
  239. // Token. If it's expired, it will be auto-refreshed using the
  240. // new TokenSource.
  241. type reuseTokenSource struct {
  242. new TokenSource // called when t is expired.
  243. mu sync.Mutex // guards t
  244. t *Token
  245. }
  246. // Token returns the current token if it's still valid, else will
  247. // refresh the current token (using r.Context for HTTP client
  248. // information) and return the new one.
  249. func (s *reuseTokenSource) Token() (*Token, error) {
  250. s.mu.Lock()
  251. defer s.mu.Unlock()
  252. if s.t.Valid() {
  253. return s.t, nil
  254. }
  255. t, err := s.new.Token()
  256. if err != nil {
  257. return nil, err
  258. }
  259. s.t = t
  260. return t, nil
  261. }
  262. // StaticTokenSource returns a TokenSource that always returns the same token.
  263. // Because the provided token t is never refreshed, StaticTokenSource is only
  264. // useful for tokens that never expire.
  265. func StaticTokenSource(t *Token) TokenSource {
  266. return staticTokenSource{t}
  267. }
  268. // staticTokenSource is a TokenSource that always returns the same Token.
  269. type staticTokenSource struct {
  270. t *Token
  271. }
  272. func (s staticTokenSource) Token() (*Token, error) {
  273. return s.t, nil
  274. }
  275. // HTTPClient is the context key to use with golang.org/x/net/context's
  276. // WithValue function to associate an *http.Client value with a context.
  277. var HTTPClient internal.ContextKey
  278. // NewClient creates an *http.Client from a Context and TokenSource.
  279. // The returned client is not valid beyond the lifetime of the context.
  280. //
  281. // Note that if a custom *http.Client is provided via the Context it
  282. // is used only for token acquisition and is not used to configure the
  283. // *http.Client returned from NewClient.
  284. //
  285. // As a special case, if src is nil, a non-OAuth2 client is returned
  286. // using the provided context. This exists to support related OAuth2
  287. // packages.
  288. func NewClient(ctx context.Context, src TokenSource) *http.Client {
  289. if src == nil {
  290. return internal.ContextClient(ctx)
  291. }
  292. return &http.Client{
  293. Transport: &Transport{
  294. Base: internal.ContextClient(ctx).Transport,
  295. Source: ReuseTokenSource(nil, src),
  296. },
  297. }
  298. }
  299. // ReuseTokenSource returns a TokenSource which repeatedly returns the
  300. // same token as long as it's valid, starting with t.
  301. // When its cached token is invalid, a new token is obtained from src.
  302. //
  303. // ReuseTokenSource is typically used to reuse tokens from a cache
  304. // (such as a file on disk) between runs of a program, rather than
  305. // obtaining new tokens unnecessarily.
  306. //
  307. // The initial token t may be nil, in which case the TokenSource is
  308. // wrapped in a caching version if it isn't one already. This also
  309. // means it's always safe to wrap ReuseTokenSource around any other
  310. // TokenSource without adverse effects.
  311. func ReuseTokenSource(t *Token, src TokenSource) TokenSource {
  312. // Don't wrap a reuseTokenSource in itself. That would work,
  313. // but cause an unnecessary number of mutex operations.
  314. // Just build the equivalent one.
  315. if rt, ok := src.(*reuseTokenSource); ok {
  316. if t == nil {
  317. // Just use it directly.
  318. return rt
  319. }
  320. src = rt.new
  321. }
  322. return &reuseTokenSource{
  323. t: t,
  324. new: src,
  325. }
  326. }