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.

oauth2.go 11KB

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