token.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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
  5. import (
  6. "context"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "golang.org/x/oauth2/internal"
  14. )
  15. // defaultExpiryDelta determines how earlier a token should be considered
  16. // expired than its actual expiration time. It is used to avoid late
  17. // expirations due to client-server time mismatches.
  18. const defaultExpiryDelta = 10 * time.Second
  19. // Token represents the credentials used to authorize
  20. // the requests to access protected resources on the OAuth 2.0
  21. // provider's backend.
  22. //
  23. // Most users of this package should not access fields of Token
  24. // directly. They're exported mostly for use by related packages
  25. // implementing derivative OAuth2 flows.
  26. type Token struct {
  27. // AccessToken is the token that authorizes and authenticates
  28. // the requests.
  29. AccessToken string `json:"access_token"`
  30. // TokenType is the type of token.
  31. // The Type method returns either this or "Bearer", the default.
  32. TokenType string `json:"token_type,omitempty"`
  33. // RefreshToken is a token that's used by the application
  34. // (as opposed to the user) to refresh the access token
  35. // if it expires.
  36. RefreshToken string `json:"refresh_token,omitempty"`
  37. // Expiry is the optional expiration time of the access token.
  38. //
  39. // If zero, [TokenSource] implementations will reuse the same
  40. // token forever and RefreshToken or equivalent
  41. // mechanisms for that TokenSource will not be used.
  42. Expiry time.Time `json:"expiry,omitempty"`
  43. // ExpiresIn is the OAuth2 wire format "expires_in" field,
  44. // which specifies how many seconds later the token expires,
  45. // relative to an unknown time base approximately around "now".
  46. // It is the application's responsibility to populate
  47. // `Expiry` from `ExpiresIn` when required.
  48. ExpiresIn int64 `json:"expires_in,omitempty"`
  49. // raw optionally contains extra metadata from the server
  50. // when updating a token.
  51. raw any
  52. // expiryDelta is used to calculate when a token is considered
  53. // expired, by subtracting from Expiry. If zero, defaultExpiryDelta
  54. // is used.
  55. expiryDelta time.Duration
  56. }
  57. // Type returns t.TokenType if non-empty, else "Bearer".
  58. func (t *Token) Type() string {
  59. if strings.EqualFold(t.TokenType, "bearer") {
  60. return "Bearer"
  61. }
  62. if strings.EqualFold(t.TokenType, "mac") {
  63. return "MAC"
  64. }
  65. if strings.EqualFold(t.TokenType, "basic") {
  66. return "Basic"
  67. }
  68. if t.TokenType != "" {
  69. return t.TokenType
  70. }
  71. return "Bearer"
  72. }
  73. // SetAuthHeader sets the Authorization header to r using the access
  74. // token in t.
  75. //
  76. // This method is unnecessary when using [Transport] or an HTTP Client
  77. // returned by this package.
  78. func (t *Token) SetAuthHeader(r *http.Request) {
  79. r.Header.Set("Authorization", t.Type()+" "+t.AccessToken)
  80. }
  81. // WithExtra returns a new [Token] that's a clone of t, but using the
  82. // provided raw extra map. This is only intended for use by packages
  83. // implementing derivative OAuth2 flows.
  84. func (t *Token) WithExtra(extra any) *Token {
  85. t2 := new(Token)
  86. *t2 = *t
  87. t2.raw = extra
  88. return t2
  89. }
  90. // Extra returns an extra field.
  91. // Extra fields are key-value pairs returned by the server as a
  92. // part of the token retrieval response.
  93. func (t *Token) Extra(key string) any {
  94. if raw, ok := t.raw.(map[string]any); ok {
  95. return raw[key]
  96. }
  97. vals, ok := t.raw.(url.Values)
  98. if !ok {
  99. return nil
  100. }
  101. v := vals.Get(key)
  102. switch s := strings.TrimSpace(v); strings.Count(s, ".") {
  103. case 0: // Contains no "."; try to parse as int
  104. if i, err := strconv.ParseInt(s, 10, 64); err == nil {
  105. return i
  106. }
  107. case 1: // Contains a single "."; try to parse as float
  108. if f, err := strconv.ParseFloat(s, 64); err == nil {
  109. return f
  110. }
  111. }
  112. return v
  113. }
  114. // timeNow is time.Now but pulled out as a variable for tests.
  115. var timeNow = time.Now
  116. // expired reports whether the token is expired.
  117. // t must be non-nil.
  118. func (t *Token) expired() bool {
  119. if t.Expiry.IsZero() {
  120. return false
  121. }
  122. expiryDelta := defaultExpiryDelta
  123. if t.expiryDelta != 0 {
  124. expiryDelta = t.expiryDelta
  125. }
  126. return t.Expiry.Round(0).Add(-expiryDelta).Before(timeNow())
  127. }
  128. // Valid reports whether t is non-nil, has an AccessToken, and is not expired.
  129. func (t *Token) Valid() bool {
  130. return t != nil && t.AccessToken != "" && !t.expired()
  131. }
  132. // tokenFromInternal maps an *internal.Token struct into
  133. // a *Token struct.
  134. func tokenFromInternal(t *internal.Token) *Token {
  135. if t == nil {
  136. return nil
  137. }
  138. return &Token{
  139. AccessToken: t.AccessToken,
  140. TokenType: t.TokenType,
  141. RefreshToken: t.RefreshToken,
  142. Expiry: t.Expiry,
  143. ExpiresIn: t.ExpiresIn,
  144. raw: t.Raw,
  145. }
  146. }
  147. // retrieveToken takes a *Config and uses that to retrieve an *internal.Token.
  148. // This token is then mapped from *internal.Token into an *oauth2.Token which is returned along
  149. // with an error.
  150. func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) {
  151. tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v, internal.AuthStyle(c.Endpoint.AuthStyle), c.authStyleCache.Get())
  152. if err != nil {
  153. if rErr, ok := err.(*internal.RetrieveError); ok {
  154. return nil, (*RetrieveError)(rErr)
  155. }
  156. return nil, err
  157. }
  158. return tokenFromInternal(tk), nil
  159. }
  160. // RetrieveError is the error returned when the token endpoint returns a
  161. // non-2XX HTTP status code or populates RFC 6749's 'error' parameter.
  162. // https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
  163. type RetrieveError struct {
  164. Response *http.Response
  165. // Body is the body that was consumed by reading Response.Body.
  166. // It may be truncated.
  167. Body []byte
  168. // ErrorCode is RFC 6749's 'error' parameter.
  169. ErrorCode string
  170. // ErrorDescription is RFC 6749's 'error_description' parameter.
  171. ErrorDescription string
  172. // ErrorURI is RFC 6749's 'error_uri' parameter.
  173. ErrorURI string
  174. }
  175. func (r *RetrieveError) Error() string {
  176. if r.ErrorCode != "" {
  177. s := fmt.Sprintf("oauth2: %q", r.ErrorCode)
  178. if r.ErrorDescription != "" {
  179. s += fmt.Sprintf(" %q", r.ErrorDescription)
  180. }
  181. if r.ErrorURI != "" {
  182. s += fmt.Sprintf(" %q", r.ErrorURI)
  183. }
  184. return s
  185. }
  186. return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body)
  187. }