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.

token.go 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. "net/http"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "golang.org/x/net/context"
  12. "golang.org/x/oauth2/internal"
  13. )
  14. // expiryDelta determines how earlier a token should be considered
  15. // expired than its actual expiration time. It is used to avoid late
  16. // expirations due to client-server time mismatches.
  17. const expiryDelta = 10 * time.Second
  18. // Token represents the crendentials used to authorize
  19. // the requests to access protected resources on the OAuth 2.0
  20. // provider's backend.
  21. //
  22. // Most users of this package should not access fields of Token
  23. // directly. They're exported mostly for use by related packages
  24. // implementing derivative OAuth2 flows.
  25. type Token struct {
  26. // AccessToken is the token that authorizes and authenticates
  27. // the requests.
  28. AccessToken string `json:"access_token"`
  29. // TokenType is the type of token.
  30. // The Type method returns either this or "Bearer", the default.
  31. TokenType string `json:"token_type,omitempty"`
  32. // RefreshToken is a token that's used by the application
  33. // (as opposed to the user) to refresh the access token
  34. // if it expires.
  35. RefreshToken string `json:"refresh_token,omitempty"`
  36. // Expiry is the optional expiration time of the access token.
  37. //
  38. // If zero, TokenSource implementations will reuse the same
  39. // token forever and RefreshToken or equivalent
  40. // mechanisms for that TokenSource will not be used.
  41. Expiry time.Time `json:"expiry,omitempty"`
  42. // raw optionally contains extra metadata from the server
  43. // when updating a token.
  44. raw interface{}
  45. }
  46. // Type returns t.TokenType if non-empty, else "Bearer".
  47. func (t *Token) Type() string {
  48. if strings.EqualFold(t.TokenType, "bearer") {
  49. return "Bearer"
  50. }
  51. if strings.EqualFold(t.TokenType, "mac") {
  52. return "MAC"
  53. }
  54. if strings.EqualFold(t.TokenType, "basic") {
  55. return "Basic"
  56. }
  57. if t.TokenType != "" {
  58. return t.TokenType
  59. }
  60. return "Bearer"
  61. }
  62. // SetAuthHeader sets the Authorization header to r using the access
  63. // token in t.
  64. //
  65. // This method is unnecessary when using Transport or an HTTP Client
  66. // returned by this package.
  67. func (t *Token) SetAuthHeader(r *http.Request) {
  68. r.Header.Set("Authorization", t.Type()+" "+t.AccessToken)
  69. }
  70. // WithExtra returns a new Token that's a clone of t, but using the
  71. // provided raw extra map. This is only intended for use by packages
  72. // implementing derivative OAuth2 flows.
  73. func (t *Token) WithExtra(extra interface{}) *Token {
  74. t2 := new(Token)
  75. *t2 = *t
  76. t2.raw = extra
  77. return t2
  78. }
  79. // Extra returns an extra field.
  80. // Extra fields are key-value pairs returned by the server as a
  81. // part of the token retrieval response.
  82. func (t *Token) Extra(key string) interface{} {
  83. if raw, ok := t.raw.(map[string]interface{}); ok {
  84. return raw[key]
  85. }
  86. vals, ok := t.raw.(url.Values)
  87. if !ok {
  88. return nil
  89. }
  90. v := vals.Get(key)
  91. switch s := strings.TrimSpace(v); strings.Count(s, ".") {
  92. case 0: // Contains no "."; try to parse as int
  93. if i, err := strconv.ParseInt(s, 10, 64); err == nil {
  94. return i
  95. }
  96. case 1: // Contains a single "."; try to parse as float
  97. if f, err := strconv.ParseFloat(s, 64); err == nil {
  98. return f
  99. }
  100. }
  101. return v
  102. }
  103. // expired reports whether the token is expired.
  104. // t must be non-nil.
  105. func (t *Token) expired() bool {
  106. if t.Expiry.IsZero() {
  107. return false
  108. }
  109. return t.Expiry.Add(-expiryDelta).Before(time.Now())
  110. }
  111. // Valid reports whether t is non-nil, has an AccessToken, and is not expired.
  112. func (t *Token) Valid() bool {
  113. return t != nil && t.AccessToken != "" && !t.expired()
  114. }
  115. // tokenFromInternal maps an *internal.Token struct into
  116. // a *Token struct.
  117. func tokenFromInternal(t *internal.Token) *Token {
  118. if t == nil {
  119. return nil
  120. }
  121. return &Token{
  122. AccessToken: t.AccessToken,
  123. TokenType: t.TokenType,
  124. RefreshToken: t.RefreshToken,
  125. Expiry: t.Expiry,
  126. raw: t.Raw,
  127. }
  128. }
  129. // retrieveToken takes a *Config and uses that to retrieve an *internal.Token.
  130. // This token is then mapped from *internal.Token into an *oauth2.Token which is returned along
  131. // with an error..
  132. func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) {
  133. tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return tokenFromInternal(tk), nil
  138. }