oauth2.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. "time"
  18. "golang.org/x/oauth2/internal"
  19. )
  20. // NoContext is the default context you should supply if not using
  21. // your own context.Context (see https://golang.org/x/net/context).
  22. //
  23. // Deprecated: Use context.Background() or context.TODO() instead.
  24. var NoContext = context.TODO()
  25. // RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op.
  26. //
  27. // Deprecated: this function no longer does anything. Caller code that
  28. // wants to avoid potential extra HTTP requests made during
  29. // auto-probing of the provider's auth style should set
  30. // Endpoint.AuthStyle.
  31. func RegisterBrokenAuthHeaderProvider(tokenURL string) {}
  32. // Config describes a typical 3-legged OAuth2 flow, with both the
  33. // client application information and the server's endpoint URLs.
  34. // For the client credentials 2-legged OAuth2 flow, see the clientcredentials
  35. // package (https://golang.org/x/oauth2/clientcredentials).
  36. type Config struct {
  37. // ClientID is the application's ID.
  38. ClientID string
  39. // ClientSecret is the application's secret.
  40. ClientSecret string
  41. // Endpoint contains the resource server's token endpoint
  42. // URLs. These are constants specific to each server and are
  43. // often available via site-specific packages, such as
  44. // google.Endpoint or github.Endpoint.
  45. Endpoint Endpoint
  46. // RedirectURL is the URL to redirect users going through
  47. // the OAuth flow, after the resource owner's URLs.
  48. RedirectURL string
  49. // Scope specifies optional requested permissions.
  50. Scopes []string
  51. // authStyleCache caches which auth style to use when Endpoint.AuthStyle is
  52. // the zero value (AuthStyleAutoDetect).
  53. authStyleCache internal.LazyAuthStyleCache
  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 represents an OAuth 2.0 provider's authorization and token
  63. // endpoint URLs.
  64. type Endpoint struct {
  65. AuthURL string
  66. DeviceAuthURL string
  67. TokenURL string
  68. // AuthStyle optionally specifies how the endpoint wants the
  69. // client ID & client secret sent. The zero value means to
  70. // auto-detect.
  71. AuthStyle AuthStyle
  72. }
  73. // AuthStyle represents how requests for tokens are authenticated
  74. // to the server.
  75. type AuthStyle int
  76. const (
  77. // AuthStyleAutoDetect means to auto-detect which authentication
  78. // style the provider wants by trying both ways and caching
  79. // the successful way for the future.
  80. AuthStyleAutoDetect AuthStyle = 0
  81. // AuthStyleInParams sends the "client_id" and "client_secret"
  82. // in the POST body as application/x-www-form-urlencoded parameters.
  83. AuthStyleInParams AuthStyle = 1
  84. // AuthStyleInHeader sends the client_id and client_password
  85. // using HTTP Basic Authorization. This is an optional style
  86. // described in the OAuth2 RFC 6749 section 2.3.1.
  87. AuthStyleInHeader AuthStyle = 2
  88. )
  89. var (
  90. // AccessTypeOnline and AccessTypeOffline are options passed
  91. // to the Options.AuthCodeURL method. They modify the
  92. // "access_type" field that gets sent in the URL returned by
  93. // AuthCodeURL.
  94. //
  95. // Online is the default if neither is specified. If your
  96. // application needs to refresh access tokens when the user
  97. // is not present at the browser, then use offline. This will
  98. // result in your application obtaining a refresh token the
  99. // first time your application exchanges an authorization
  100. // code for a user.
  101. AccessTypeOnline AuthCodeOption = SetAuthURLParam("access_type", "online")
  102. AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline")
  103. // ApprovalForce forces the users to view the consent dialog
  104. // and confirm the permissions request at the URL returned
  105. // from AuthCodeURL, even if they've already done so.
  106. ApprovalForce AuthCodeOption = SetAuthURLParam("prompt", "consent")
  107. )
  108. // An AuthCodeOption is passed to Config.AuthCodeURL.
  109. type AuthCodeOption interface {
  110. setValue(url.Values)
  111. }
  112. type setParam struct{ k, v string }
  113. func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) }
  114. // SetAuthURLParam builds an AuthCodeOption which passes key/value parameters
  115. // to a provider's authorization endpoint.
  116. func SetAuthURLParam(key, value string) AuthCodeOption {
  117. return setParam{key, value}
  118. }
  119. // AuthCodeURL returns a URL to OAuth 2.0 provider's consent page
  120. // that asks for permissions for the required scopes explicitly.
  121. //
  122. // State is an opaque value used by the client to maintain state between the
  123. // request and callback. The authorization server includes this value when
  124. // redirecting the user agent back to the client.
  125. //
  126. // Opts may include AccessTypeOnline or AccessTypeOffline, as well
  127. // as ApprovalForce.
  128. //
  129. // To protect against CSRF attacks, opts should include a PKCE challenge
  130. // (S256ChallengeOption). Not all servers support PKCE. An alternative is to
  131. // generate a random state parameter and verify it after exchange.
  132. // See https://datatracker.ietf.org/doc/html/rfc6749#section-10.12 (predating
  133. // PKCE), https://www.oauth.com/oauth2-servers/pkce/ and
  134. // https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-09.html#name-cross-site-request-forgery (describing both approaches)
  135. func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string {
  136. var buf bytes.Buffer
  137. buf.WriteString(c.Endpoint.AuthURL)
  138. v := url.Values{
  139. "response_type": {"code"},
  140. "client_id": {c.ClientID},
  141. }
  142. if c.RedirectURL != "" {
  143. v.Set("redirect_uri", c.RedirectURL)
  144. }
  145. if len(c.Scopes) > 0 {
  146. v.Set("scope", strings.Join(c.Scopes, " "))
  147. }
  148. if state != "" {
  149. v.Set("state", state)
  150. }
  151. for _, opt := range opts {
  152. opt.setValue(v)
  153. }
  154. if strings.Contains(c.Endpoint.AuthURL, "?") {
  155. buf.WriteByte('&')
  156. } else {
  157. buf.WriteByte('?')
  158. }
  159. buf.WriteString(v.Encode())
  160. return buf.String()
  161. }
  162. // PasswordCredentialsToken converts a resource owner username and password
  163. // pair into a token.
  164. //
  165. // Per the RFC, this grant type should only be used "when there is a high
  166. // degree of trust between the resource owner and the client (e.g., the client
  167. // is part of the device operating system or a highly privileged application),
  168. // and when other authorization grant types are not available."
  169. // See https://tools.ietf.org/html/rfc6749#section-4.3 for more info.
  170. //
  171. // The provided context optionally controls which HTTP client is used. See the HTTPClient variable.
  172. func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) {
  173. v := url.Values{
  174. "grant_type": {"password"},
  175. "username": {username},
  176. "password": {password},
  177. }
  178. if len(c.Scopes) > 0 {
  179. v.Set("scope", strings.Join(c.Scopes, " "))
  180. }
  181. return retrieveToken(ctx, c, v)
  182. }
  183. // Exchange converts an authorization code into a token.
  184. //
  185. // It is used after a resource provider redirects the user back
  186. // to the Redirect URI (the URL obtained from AuthCodeURL).
  187. //
  188. // The provided context optionally controls which HTTP client is used. See the HTTPClient variable.
  189. //
  190. // The code will be in the *http.Request.FormValue("code"). Before
  191. // calling Exchange, be sure to validate FormValue("state") if you are
  192. // using it to protect against CSRF attacks.
  193. //
  194. // If using PKCE to protect against CSRF attacks, opts should include a
  195. // VerifierOption.
  196. func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error) {
  197. v := url.Values{
  198. "grant_type": {"authorization_code"},
  199. "code": {code},
  200. }
  201. if c.RedirectURL != "" {
  202. v.Set("redirect_uri", c.RedirectURL)
  203. }
  204. for _, opt := range opts {
  205. opt.setValue(v)
  206. }
  207. return retrieveToken(ctx, c, v)
  208. }
  209. // Client returns an HTTP client using the provided token.
  210. // The token will auto-refresh as necessary. The underlying
  211. // HTTP transport will be obtained using the provided context.
  212. // The returned client and its Transport should not be modified.
  213. func (c *Config) Client(ctx context.Context, t *Token) *http.Client {
  214. return NewClient(ctx, c.TokenSource(ctx, t))
  215. }
  216. // TokenSource returns a TokenSource that returns t until t expires,
  217. // automatically refreshing it as necessary using the provided context.
  218. //
  219. // Most users will use Config.Client instead.
  220. func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource {
  221. tkr := &tokenRefresher{
  222. ctx: ctx,
  223. conf: c,
  224. }
  225. if t != nil {
  226. tkr.refreshToken = t.RefreshToken
  227. }
  228. return &reuseTokenSource{
  229. t: t,
  230. new: tkr,
  231. }
  232. }
  233. // tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token"
  234. // HTTP requests to renew a token using a RefreshToken.
  235. type tokenRefresher struct {
  236. ctx context.Context // used to get HTTP requests
  237. conf *Config
  238. refreshToken string
  239. }
  240. // WARNING: Token is not safe for concurrent access, as it
  241. // updates the tokenRefresher's refreshToken field.
  242. // Within this package, it is used by reuseTokenSource which
  243. // synchronizes calls to this method with its own mutex.
  244. func (tf *tokenRefresher) Token() (*Token, error) {
  245. if tf.refreshToken == "" {
  246. return nil, errors.New("oauth2: token expired and refresh token is not set")
  247. }
  248. tk, err := retrieveToken(tf.ctx, tf.conf, url.Values{
  249. "grant_type": {"refresh_token"},
  250. "refresh_token": {tf.refreshToken},
  251. })
  252. if err != nil {
  253. return nil, err
  254. }
  255. if tf.refreshToken != tk.RefreshToken {
  256. tf.refreshToken = tk.RefreshToken
  257. }
  258. return tk, err
  259. }
  260. // reuseTokenSource is a TokenSource that holds a single token in memory
  261. // and validates its expiry before each call to retrieve it with
  262. // Token. If it's expired, it will be auto-refreshed using the
  263. // new TokenSource.
  264. type reuseTokenSource struct {
  265. new TokenSource // called when t is expired.
  266. mu sync.Mutex // guards t
  267. t *Token
  268. expiryDelta time.Duration
  269. }
  270. // Token returns the current token if it's still valid, else will
  271. // refresh the current token (using r.Context for HTTP client
  272. // information) and return the new one.
  273. func (s *reuseTokenSource) Token() (*Token, error) {
  274. s.mu.Lock()
  275. defer s.mu.Unlock()
  276. if s.t.Valid() {
  277. return s.t, nil
  278. }
  279. t, err := s.new.Token()
  280. if err != nil {
  281. return nil, err
  282. }
  283. t.expiryDelta = s.expiryDelta
  284. s.t = t
  285. return t, nil
  286. }
  287. // StaticTokenSource returns a TokenSource that always returns the same token.
  288. // Because the provided token t is never refreshed, StaticTokenSource is only
  289. // useful for tokens that never expire.
  290. func StaticTokenSource(t *Token) TokenSource {
  291. return staticTokenSource{t}
  292. }
  293. // staticTokenSource is a TokenSource that always returns the same Token.
  294. type staticTokenSource struct {
  295. t *Token
  296. }
  297. func (s staticTokenSource) Token() (*Token, error) {
  298. return s.t, nil
  299. }
  300. // HTTPClient is the context key to use with golang.org/x/net/context's
  301. // WithValue function to associate an *http.Client value with a context.
  302. var HTTPClient internal.ContextKey
  303. // NewClient creates an *http.Client from a Context and TokenSource.
  304. // The returned client is not valid beyond the lifetime of the context.
  305. //
  306. // Note that if a custom *http.Client is provided via the Context it
  307. // is used only for token acquisition and is not used to configure the
  308. // *http.Client returned from NewClient.
  309. //
  310. // As a special case, if src is nil, a non-OAuth2 client is returned
  311. // using the provided context. This exists to support related OAuth2
  312. // packages.
  313. func NewClient(ctx context.Context, src TokenSource) *http.Client {
  314. if src == nil {
  315. return internal.ContextClient(ctx)
  316. }
  317. return &http.Client{
  318. Transport: &Transport{
  319. Base: internal.ContextClient(ctx).Transport,
  320. Source: ReuseTokenSource(nil, src),
  321. },
  322. }
  323. }
  324. // ReuseTokenSource returns a TokenSource which repeatedly returns the
  325. // same token as long as it's valid, starting with t.
  326. // When its cached token is invalid, a new token is obtained from src.
  327. //
  328. // ReuseTokenSource is typically used to reuse tokens from a cache
  329. // (such as a file on disk) between runs of a program, rather than
  330. // obtaining new tokens unnecessarily.
  331. //
  332. // The initial token t may be nil, in which case the TokenSource is
  333. // wrapped in a caching version if it isn't one already. This also
  334. // means it's always safe to wrap ReuseTokenSource around any other
  335. // TokenSource without adverse effects.
  336. func ReuseTokenSource(t *Token, src TokenSource) TokenSource {
  337. // Don't wrap a reuseTokenSource in itself. That would work,
  338. // but cause an unnecessary number of mutex operations.
  339. // Just build the equivalent one.
  340. if rt, ok := src.(*reuseTokenSource); ok {
  341. if t == nil {
  342. // Just use it directly.
  343. return rt
  344. }
  345. src = rt.new
  346. }
  347. return &reuseTokenSource{
  348. t: t,
  349. new: src,
  350. }
  351. }
  352. // ReuseTokenSource returns a TokenSource that acts in the same manner as the
  353. // TokenSource returned by ReuseTokenSource, except the expiry buffer is
  354. // configurable. The expiration time of a token is calculated as
  355. // t.Expiry.Add(-earlyExpiry).
  356. func ReuseTokenSourceWithExpiry(t *Token, src TokenSource, earlyExpiry time.Duration) TokenSource {
  357. // Don't wrap a reuseTokenSource in itself. That would work,
  358. // but cause an unnecessary number of mutex operations.
  359. // Just build the equivalent one.
  360. if rt, ok := src.(*reuseTokenSource); ok {
  361. if t == nil {
  362. // Just use it directly, but set the expiryDelta to earlyExpiry,
  363. // so the behavior matches what the user expects.
  364. rt.expiryDelta = earlyExpiry
  365. return rt
  366. }
  367. src = rt.new
  368. }
  369. if t != nil {
  370. t.expiryDelta = earlyExpiry
  371. }
  372. return &reuseTokenSource{
  373. t: t,
  374. new: src,
  375. expiryDelta: earlyExpiry,
  376. }
  377. }