oauth2.go 13 KB

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