oauth2.go 13 KB

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