oauth2.go 11 KB

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