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.
 
 
 

269 lines
7.8 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 internal
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime"
  12. "net/http"
  13. "net/url"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "golang.org/x/net/context"
  18. "golang.org/x/net/context/ctxhttp"
  19. )
  20. // Token represents the credentials used to authorize
  21. // the requests to access protected resources on the OAuth 2.0
  22. // provider's backend.
  23. //
  24. // This type is a mirror of oauth2.Token and exists to break
  25. // an otherwise-circular dependency. Other internal packages
  26. // should convert this Token into an oauth2.Token before use.
  27. type Token struct {
  28. // AccessToken is the token that authorizes and authenticates
  29. // the requests.
  30. AccessToken string
  31. // TokenType is the type of token.
  32. // The Type method returns either this or "Bearer", the default.
  33. TokenType string
  34. // RefreshToken is a token that's used by the application
  35. // (as opposed to the user) to refresh the access token
  36. // if it expires.
  37. RefreshToken string
  38. // Expiry is the optional expiration time of the access token.
  39. //
  40. // If zero, TokenSource implementations will reuse the same
  41. // token forever and RefreshToken or equivalent
  42. // mechanisms for that TokenSource will not be used.
  43. Expiry time.Time
  44. // Raw optionally contains extra metadata from the server
  45. // when updating a token.
  46. Raw interface{}
  47. }
  48. // tokenJSON is the struct representing the HTTP response from OAuth2
  49. // providers returning a token in JSON form.
  50. type tokenJSON struct {
  51. AccessToken string `json:"access_token"`
  52. TokenType string `json:"token_type"`
  53. RefreshToken string `json:"refresh_token"`
  54. ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number
  55. Expires expirationTime `json:"expires"` // broken Facebook spelling of expires_in
  56. }
  57. func (e *tokenJSON) expiry() (t time.Time) {
  58. if v := e.ExpiresIn; v != 0 {
  59. return time.Now().Add(time.Duration(v) * time.Second)
  60. }
  61. if v := e.Expires; v != 0 {
  62. return time.Now().Add(time.Duration(v) * time.Second)
  63. }
  64. return
  65. }
  66. type expirationTime int32
  67. func (e *expirationTime) UnmarshalJSON(b []byte) error {
  68. var n json.Number
  69. err := json.Unmarshal(b, &n)
  70. if err != nil {
  71. return err
  72. }
  73. i, err := n.Int64()
  74. if err != nil {
  75. return err
  76. }
  77. *e = expirationTime(i)
  78. return nil
  79. }
  80. var brokenAuthHeaderProviders = []string{
  81. "https://accounts.google.com/",
  82. "https://api.codeswholesale.com/oauth/token",
  83. "https://api.dropbox.com/",
  84. "https://api.dropboxapi.com/",
  85. "https://api.instagram.com/",
  86. "https://api.netatmo.net/",
  87. "https://api.odnoklassniki.ru/",
  88. "https://api.pushbullet.com/",
  89. "https://api.soundcloud.com/",
  90. "https://api.twitch.tv/",
  91. "https://app.box.com/",
  92. "https://connect.stripe.com/",
  93. "https://login.mailchimp.com/",
  94. "https://login.microsoftonline.com/",
  95. "https://login.salesforce.com/",
  96. "https://login.windows.net",
  97. "https://login.live.com/",
  98. "https://oauth.sandbox.trainingpeaks.com/",
  99. "https://oauth.trainingpeaks.com/",
  100. "https://oauth.vk.com/",
  101. "https://openapi.baidu.com/",
  102. "https://slack.com/",
  103. "https://test-sandbox.auth.corp.google.com",
  104. "https://test.salesforce.com/",
  105. "https://user.gini.net/",
  106. "https://www.douban.com/",
  107. "https://www.googleapis.com/",
  108. "https://www.linkedin.com/",
  109. "https://www.strava.com/oauth/",
  110. "https://www.wunderlist.com/oauth/",
  111. "https://api.patreon.com/",
  112. "https://sandbox.codeswholesale.com/oauth/token",
  113. "https://api.sipgate.com/v1/authorization/oauth",
  114. "https://api.medium.com/v1/tokens",
  115. "https://log.finalsurge.com/oauth/token",
  116. "https://multisport.todaysplan.com.au/rest/oauth/access_token",
  117. "https://whats.todaysplan.com.au/rest/oauth/access_token",
  118. }
  119. // brokenAuthHeaderDomains lists broken providers that issue dynamic endpoints.
  120. var brokenAuthHeaderDomains = []string{
  121. ".auth0.com",
  122. ".force.com",
  123. ".myshopify.com",
  124. ".okta.com",
  125. ".oktapreview.com",
  126. }
  127. func RegisterBrokenAuthHeaderProvider(tokenURL string) {
  128. brokenAuthHeaderProviders = append(brokenAuthHeaderProviders, tokenURL)
  129. }
  130. // providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL
  131. // implements the OAuth2 spec correctly
  132. // See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
  133. // In summary:
  134. // - Reddit only accepts client secret in the Authorization header
  135. // - Dropbox accepts either it in URL param or Auth header, but not both.
  136. // - Google only accepts URL param (not spec compliant?), not Auth header
  137. // - Stripe only accepts client secret in Auth header with Bearer method, not Basic
  138. func providerAuthHeaderWorks(tokenURL string) bool {
  139. for _, s := range brokenAuthHeaderProviders {
  140. if strings.HasPrefix(tokenURL, s) {
  141. // Some sites fail to implement the OAuth2 spec fully.
  142. return false
  143. }
  144. }
  145. if u, err := url.Parse(tokenURL); err == nil {
  146. for _, s := range brokenAuthHeaderDomains {
  147. if strings.HasSuffix(u.Host, s) {
  148. return false
  149. }
  150. }
  151. }
  152. // Assume the provider implements the spec properly
  153. // otherwise. We can add more exceptions as they're
  154. // discovered. We will _not_ be adding configurable hooks
  155. // to this package to let users select server bugs.
  156. return true
  157. }
  158. func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error) {
  159. bustedAuth := !providerAuthHeaderWorks(tokenURL)
  160. if bustedAuth {
  161. if clientID != "" {
  162. v.Set("client_id", clientID)
  163. }
  164. if clientSecret != "" {
  165. v.Set("client_secret", clientSecret)
  166. }
  167. }
  168. req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode()))
  169. if err != nil {
  170. return nil, err
  171. }
  172. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  173. if !bustedAuth {
  174. req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret))
  175. }
  176. r, err := ctxhttp.Do(ctx, ContextClient(ctx), req)
  177. if err != nil {
  178. return nil, err
  179. }
  180. defer r.Body.Close()
  181. body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
  182. if err != nil {
  183. return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
  184. }
  185. if code := r.StatusCode; code < 200 || code > 299 {
  186. return nil, &RetrieveError{
  187. Response: r,
  188. Body: body,
  189. }
  190. }
  191. var token *Token
  192. content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
  193. switch content {
  194. case "application/x-www-form-urlencoded", "text/plain":
  195. vals, err := url.ParseQuery(string(body))
  196. if err != nil {
  197. return nil, err
  198. }
  199. token = &Token{
  200. AccessToken: vals.Get("access_token"),
  201. TokenType: vals.Get("token_type"),
  202. RefreshToken: vals.Get("refresh_token"),
  203. Raw: vals,
  204. }
  205. e := vals.Get("expires_in")
  206. if e == "" {
  207. // TODO(jbd): Facebook's OAuth2 implementation is broken and
  208. // returns expires_in field in expires. Remove the fallback to expires,
  209. // when Facebook fixes their implementation.
  210. e = vals.Get("expires")
  211. }
  212. expires, _ := strconv.Atoi(e)
  213. if expires != 0 {
  214. token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
  215. }
  216. default:
  217. var tj tokenJSON
  218. if err = json.Unmarshal(body, &tj); err != nil {
  219. return nil, err
  220. }
  221. token = &Token{
  222. AccessToken: tj.AccessToken,
  223. TokenType: tj.TokenType,
  224. RefreshToken: tj.RefreshToken,
  225. Expiry: tj.expiry(),
  226. Raw: make(map[string]interface{}),
  227. }
  228. json.Unmarshal(body, &token.Raw) // no error checks for optional fields
  229. }
  230. // Don't overwrite `RefreshToken` with an empty value
  231. // if this was a token refreshing request.
  232. if token.RefreshToken == "" {
  233. token.RefreshToken = v.Get("refresh_token")
  234. }
  235. if token.AccessToken == "" {
  236. return token, errors.New("oauth2: server response missing access_token")
  237. }
  238. return token, nil
  239. }
  240. type RetrieveError struct {
  241. Response *http.Response
  242. Body []byte
  243. }
  244. func (r *RetrieveError) Error() string {
  245. return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body)
  246. }