token.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. // raw optionally contains extra metadata from the server
  44. // when updating a token.
  45. raw interface{}
  46. // expiryDelta is used to calculate when a token is considered
  47. // expired, by subtracting from Expiry. If zero, defaultExpiryDelta
  48. // is used.
  49. expiryDelta time.Duration
  50. }
  51. // Type returns t.TokenType if non-empty, else "Bearer".
  52. func (t *Token) Type() string {
  53. if strings.EqualFold(t.TokenType, "bearer") {
  54. return "Bearer"
  55. }
  56. if strings.EqualFold(t.TokenType, "mac") {
  57. return "MAC"
  58. }
  59. if strings.EqualFold(t.TokenType, "basic") {
  60. return "Basic"
  61. }
  62. if t.TokenType != "" {
  63. return t.TokenType
  64. }
  65. return "Bearer"
  66. }
  67. // SetAuthHeader sets the Authorization header to r using the access
  68. // token in t.
  69. //
  70. // This method is unnecessary when using Transport or an HTTP Client
  71. // returned by this package.
  72. func (t *Token) SetAuthHeader(r *http.Request) {
  73. r.Header.Set("Authorization", t.Type()+" "+t.AccessToken)
  74. }
  75. // WithExtra returns a new Token that's a clone of t, but using the
  76. // provided raw extra map. This is only intended for use by packages
  77. // implementing derivative OAuth2 flows.
  78. func (t *Token) WithExtra(extra interface{}) *Token {
  79. t2 := new(Token)
  80. *t2 = *t
  81. t2.raw = extra
  82. return t2
  83. }
  84. // Extra returns an extra field.
  85. // Extra fields are key-value pairs returned by the server as a
  86. // part of the token retrieval response.
  87. func (t *Token) Extra(key string) interface{} {
  88. if raw, ok := t.raw.(map[string]interface{}); ok {
  89. return raw[key]
  90. }
  91. vals, ok := t.raw.(url.Values)
  92. if !ok {
  93. return nil
  94. }
  95. v := vals.Get(key)
  96. switch s := strings.TrimSpace(v); strings.Count(s, ".") {
  97. case 0: // Contains no "."; try to parse as int
  98. if i, err := strconv.ParseInt(s, 10, 64); err == nil {
  99. return i
  100. }
  101. case 1: // Contains a single "."; try to parse as float
  102. if f, err := strconv.ParseFloat(s, 64); err == nil {
  103. return f
  104. }
  105. }
  106. return v
  107. }
  108. // timeNow is time.Now but pulled out as a variable for tests.
  109. var timeNow = time.Now
  110. // expired reports whether the token is expired.
  111. // t must be non-nil.
  112. func (t *Token) expired() bool {
  113. if t.Expiry.IsZero() {
  114. return false
  115. }
  116. expiryDelta := defaultExpiryDelta
  117. if t.expiryDelta != 0 {
  118. expiryDelta = t.expiryDelta
  119. }
  120. return t.Expiry.Round(0).Add(-expiryDelta).Before(timeNow())
  121. }
  122. // Valid reports whether t is non-nil, has an AccessToken, and is not expired.
  123. func (t *Token) Valid() bool {
  124. return t != nil && t.AccessToken != "" && !t.expired()
  125. }
  126. // tokenFromInternal maps an *internal.Token struct into
  127. // a *Token struct.
  128. func tokenFromInternal(t *internal.Token) *Token {
  129. if t == nil {
  130. return nil
  131. }
  132. return &Token{
  133. AccessToken: t.AccessToken,
  134. TokenType: t.TokenType,
  135. RefreshToken: t.RefreshToken,
  136. Expiry: t.Expiry,
  137. raw: t.Raw,
  138. }
  139. }
  140. // retrieveToken takes a *Config and uses that to retrieve an *internal.Token.
  141. // This token is then mapped from *internal.Token into an *oauth2.Token which is returned along
  142. // with an error..
  143. func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) {
  144. tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v, internal.AuthStyle(c.Endpoint.AuthStyle), c.authStyleCache.Get())
  145. if err != nil {
  146. if rErr, ok := err.(*internal.RetrieveError); ok {
  147. return nil, (*RetrieveError)(rErr)
  148. }
  149. return nil, err
  150. }
  151. return tokenFromInternal(tk), nil
  152. }
  153. // RetrieveError is the error returned when the token endpoint returns a
  154. // non-2XX HTTP status code or populates RFC 6749's 'error' parameter.
  155. // https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
  156. type RetrieveError struct {
  157. Response *http.Response
  158. // Body is the body that was consumed by reading Response.Body.
  159. // It may be truncated.
  160. Body []byte
  161. // ErrorCode is RFC 6749's 'error' parameter.
  162. ErrorCode string
  163. // ErrorDescription is RFC 6749's 'error_description' parameter.
  164. ErrorDescription string
  165. // ErrorURI is RFC 6749's 'error_uri' parameter.
  166. ErrorURI string
  167. }
  168. func (r *RetrieveError) Error() string {
  169. if r.ErrorCode != "" {
  170. s := fmt.Sprintf("oauth2: %q", r.ErrorCode)
  171. if r.ErrorDescription != "" {
  172. s += fmt.Sprintf(" %q", r.ErrorDescription)
  173. }
  174. if r.ErrorURI != "" {
  175. s += fmt.Sprintf(" %q", r.ErrorURI)
  176. }
  177. return s
  178. }
  179. return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body)
  180. }