本站源代码
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.

295 lines
8.6KB

  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 internal
  5. import (
  6. "context"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "math"
  13. "mime"
  14. "net/http"
  15. "net/url"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "golang.org/x/net/context/ctxhttp"
  21. )
  22. // Token represents the credentials used to authorize
  23. // the requests to access protected resources on the OAuth 2.0
  24. // provider's backend.
  25. //
  26. // This type is a mirror of oauth2.Token and exists to break
  27. // an otherwise-circular dependency. Other internal packages
  28. // should convert this Token into an oauth2.Token before use.
  29. type Token struct {
  30. // AccessToken is the token that authorizes and authenticates
  31. // the requests.
  32. AccessToken string
  33. // TokenType is the type of token.
  34. // The Type method returns either this or "Bearer", the default.
  35. TokenType string
  36. // RefreshToken is a token that's used by the application
  37. // (as opposed to the user) to refresh the access token
  38. // if it expires.
  39. RefreshToken string
  40. // Expiry is the optional expiration time of the access token.
  41. //
  42. // If zero, TokenSource implementations will reuse the same
  43. // token forever and RefreshToken or equivalent
  44. // mechanisms for that TokenSource will not be used.
  45. Expiry time.Time
  46. // Raw optionally contains extra metadata from the server
  47. // when updating a token.
  48. Raw interface{}
  49. }
  50. // tokenJSON is the struct representing the HTTP response from OAuth2
  51. // providers returning a token in JSON form.
  52. type tokenJSON struct {
  53. AccessToken string `json:"access_token"`
  54. TokenType string `json:"token_type"`
  55. RefreshToken string `json:"refresh_token"`
  56. ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number
  57. }
  58. func (e *tokenJSON) expiry() (t time.Time) {
  59. if v := e.ExpiresIn; v != 0 {
  60. return time.Now().Add(time.Duration(v) * time.Second)
  61. }
  62. return
  63. }
  64. type expirationTime int32
  65. func (e *expirationTime) UnmarshalJSON(b []byte) error {
  66. if len(b) == 0 || string(b) == "null" {
  67. return nil
  68. }
  69. var n json.Number
  70. err := json.Unmarshal(b, &n)
  71. if err != nil {
  72. return err
  73. }
  74. i, err := n.Int64()
  75. if err != nil {
  76. return err
  77. }
  78. if i > math.MaxInt32 {
  79. i = math.MaxInt32
  80. }
  81. *e = expirationTime(i)
  82. return nil
  83. }
  84. // RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op.
  85. //
  86. // Deprecated: this function no longer does anything. Caller code that
  87. // wants to avoid potential extra HTTP requests made during
  88. // auto-probing of the provider's auth style should set
  89. // Endpoint.AuthStyle.
  90. func RegisterBrokenAuthHeaderProvider(tokenURL string) {}
  91. // AuthStyle is a copy of the golang.org/x/oauth2 package's AuthStyle type.
  92. type AuthStyle int
  93. const (
  94. AuthStyleUnknown AuthStyle = 0
  95. AuthStyleInParams AuthStyle = 1
  96. AuthStyleInHeader AuthStyle = 2
  97. )
  98. // authStyleCache is the set of tokenURLs we've successfully used via
  99. // RetrieveToken and which style auth we ended up using.
  100. // It's called a cache, but it doesn't (yet?) shrink. It's expected that
  101. // the set of OAuth2 servers a program contacts over time is fixed and
  102. // small.
  103. var authStyleCache struct {
  104. sync.Mutex
  105. m map[string]AuthStyle // keyed by tokenURL
  106. }
  107. // ResetAuthCache resets the global authentication style cache used
  108. // for AuthStyleUnknown token requests.
  109. func ResetAuthCache() {
  110. authStyleCache.Lock()
  111. defer authStyleCache.Unlock()
  112. authStyleCache.m = nil
  113. }
  114. // lookupAuthStyle reports which auth style we last used with tokenURL
  115. // when calling RetrieveToken and whether we have ever done so.
  116. func lookupAuthStyle(tokenURL string) (style AuthStyle, ok bool) {
  117. authStyleCache.Lock()
  118. defer authStyleCache.Unlock()
  119. style, ok = authStyleCache.m[tokenURL]
  120. return
  121. }
  122. // setAuthStyle adds an entry to authStyleCache, documented above.
  123. func setAuthStyle(tokenURL string, v AuthStyle) {
  124. authStyleCache.Lock()
  125. defer authStyleCache.Unlock()
  126. if authStyleCache.m == nil {
  127. authStyleCache.m = make(map[string]AuthStyle)
  128. }
  129. authStyleCache.m[tokenURL] = v
  130. }
  131. // newTokenRequest returns a new *http.Request to retrieve a new token
  132. // from tokenURL using the provided clientID, clientSecret, and POST
  133. // body parameters.
  134. //
  135. // inParams is whether the clientID & clientSecret should be encoded
  136. // as the POST body. An 'inParams' value of true means to send it in
  137. // the POST body (along with any values in v); false means to send it
  138. // in the Authorization header.
  139. func newTokenRequest(tokenURL, clientID, clientSecret string, v url.Values, authStyle AuthStyle) (*http.Request, error) {
  140. if authStyle == AuthStyleInParams {
  141. v = cloneURLValues(v)
  142. if clientID != "" {
  143. v.Set("client_id", clientID)
  144. }
  145. if clientSecret != "" {
  146. v.Set("client_secret", clientSecret)
  147. }
  148. }
  149. req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode()))
  150. if err != nil {
  151. return nil, err
  152. }
  153. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  154. if authStyle == AuthStyleInHeader {
  155. req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret))
  156. }
  157. return req, nil
  158. }
  159. func cloneURLValues(v url.Values) url.Values {
  160. v2 := make(url.Values, len(v))
  161. for k, vv := range v {
  162. v2[k] = append([]string(nil), vv...)
  163. }
  164. return v2
  165. }
  166. func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values, authStyle AuthStyle) (*Token, error) {
  167. needsAuthStyleProbe := authStyle == 0
  168. if needsAuthStyleProbe {
  169. if style, ok := lookupAuthStyle(tokenURL); ok {
  170. authStyle = style
  171. needsAuthStyleProbe = false
  172. } else {
  173. authStyle = AuthStyleInHeader // the first way we'll try
  174. }
  175. }
  176. req, err := newTokenRequest(tokenURL, clientID, clientSecret, v, authStyle)
  177. if err != nil {
  178. return nil, err
  179. }
  180. token, err := doTokenRoundTrip(ctx, req)
  181. if err != nil && needsAuthStyleProbe {
  182. // If we get an error, assume the server wants the
  183. // clientID & clientSecret in a different form.
  184. // See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
  185. // In summary:
  186. // - Reddit only accepts client secret in the Authorization header
  187. // - Dropbox accepts either it in URL param or Auth header, but not both.
  188. // - Google only accepts URL param (not spec compliant?), not Auth header
  189. // - Stripe only accepts client secret in Auth header with Bearer method, not Basic
  190. //
  191. // We used to maintain a big table in this code of all the sites and which way
  192. // they went, but maintaining it didn't scale & got annoying.
  193. // So just try both ways.
  194. authStyle = AuthStyleInParams // the second way we'll try
  195. req, _ = newTokenRequest(tokenURL, clientID, clientSecret, v, authStyle)
  196. token, err = doTokenRoundTrip(ctx, req)
  197. }
  198. if needsAuthStyleProbe && err == nil {
  199. setAuthStyle(tokenURL, authStyle)
  200. }
  201. // Don't overwrite `RefreshToken` with an empty value
  202. // if this was a token refreshing request.
  203. if token != nil && token.RefreshToken == "" {
  204. token.RefreshToken = v.Get("refresh_token")
  205. }
  206. return token, err
  207. }
  208. func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) {
  209. r, err := ctxhttp.Do(ctx, ContextClient(ctx), req)
  210. if err != nil {
  211. return nil, err
  212. }
  213. body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
  214. r.Body.Close()
  215. if err != nil {
  216. return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
  217. }
  218. if code := r.StatusCode; code < 200 || code > 299 {
  219. return nil, &RetrieveError{
  220. Response: r,
  221. Body: body,
  222. }
  223. }
  224. var token *Token
  225. content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
  226. switch content {
  227. case "application/x-www-form-urlencoded", "text/plain":
  228. vals, err := url.ParseQuery(string(body))
  229. if err != nil {
  230. return nil, err
  231. }
  232. token = &Token{
  233. AccessToken: vals.Get("access_token"),
  234. TokenType: vals.Get("token_type"),
  235. RefreshToken: vals.Get("refresh_token"),
  236. Raw: vals,
  237. }
  238. e := vals.Get("expires_in")
  239. expires, _ := strconv.Atoi(e)
  240. if expires != 0 {
  241. token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
  242. }
  243. default:
  244. var tj tokenJSON
  245. if err = json.Unmarshal(body, &tj); err != nil {
  246. return nil, err
  247. }
  248. token = &Token{
  249. AccessToken: tj.AccessToken,
  250. TokenType: tj.TokenType,
  251. RefreshToken: tj.RefreshToken,
  252. Expiry: tj.expiry(),
  253. Raw: make(map[string]interface{}),
  254. }
  255. json.Unmarshal(body, &token.Raw) // no error checks for optional fields
  256. }
  257. if token.AccessToken == "" {
  258. return nil, errors.New("oauth2: server response missing access_token")
  259. }
  260. return token, nil
  261. }
  262. type RetrieveError struct {
  263. Response *http.Response
  264. Body []byte
  265. }
  266. func (r *RetrieveError) Error() string {
  267. return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body)
  268. }
上海开阖软件有限公司 沪ICP备12045867号-1