25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

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