You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

382 lines
12 KiB

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