You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

token.go 6.9 kB

Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 contains support packages for oauth2 package.
  5. package internal
  6. import (
  7. "encoding/json"
  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. )
  19. // Token represents the crendentials used to authorize
  20. // the requests to access protected resources on the OAuth 2.0
  21. // provider's backend.
  22. //
  23. // This type is a mirror of oauth2.Token and exists to break
  24. // an otherwise-circular dependency. Other internal packages
  25. // should convert this Token into an oauth2.Token before use.
  26. type Token struct {
  27. // AccessToken is the token that authorizes and authenticates
  28. // the requests.
  29. AccessToken string
  30. // TokenType is the type of token.
  31. // The Type method returns either this or "Bearer", the default.
  32. TokenType string
  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
  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
  43. // Raw optionally contains extra metadata from the server
  44. // when updating a token.
  45. Raw interface{}
  46. }
  47. // tokenJSON is the struct representing the HTTP response from OAuth2
  48. // providers returning a token in JSON form.
  49. type tokenJSON struct {
  50. AccessToken string `json:"access_token"`
  51. TokenType string `json:"token_type"`
  52. RefreshToken string `json:"refresh_token"`
  53. ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number
  54. Expires expirationTime `json:"expires"` // broken Facebook spelling of expires_in
  55. }
  56. func (e *tokenJSON) expiry() (t time.Time) {
  57. if v := e.ExpiresIn; v != 0 {
  58. return time.Now().Add(time.Duration(v) * time.Second)
  59. }
  60. if v := e.Expires; v != 0 {
  61. return time.Now().Add(time.Duration(v) * time.Second)
  62. }
  63. return
  64. }
  65. type expirationTime int32
  66. func (e *expirationTime) UnmarshalJSON(b []byte) error {
  67. var n json.Number
  68. err := json.Unmarshal(b, &n)
  69. if err != nil {
  70. return err
  71. }
  72. i, err := n.Int64()
  73. if err != nil {
  74. return err
  75. }
  76. *e = expirationTime(i)
  77. return nil
  78. }
  79. var brokenAuthHeaderProviders = []string{
  80. "https://accounts.google.com/",
  81. "https://api.dropbox.com/",
  82. "https://api.dropboxapi.com/",
  83. "https://api.instagram.com/",
  84. "https://api.netatmo.net/",
  85. "https://api.odnoklassniki.ru/",
  86. "https://api.pushbullet.com/",
  87. "https://api.soundcloud.com/",
  88. "https://api.twitch.tv/",
  89. "https://app.box.com/",
  90. "https://connect.stripe.com/",
  91. "https://login.microsoftonline.com/",
  92. "https://login.salesforce.com/",
  93. "https://oauth.sandbox.trainingpeaks.com/",
  94. "https://oauth.trainingpeaks.com/",
  95. "https://oauth.vk.com/",
  96. "https://openapi.baidu.com/",
  97. "https://slack.com/",
  98. "https://test-sandbox.auth.corp.google.com",
  99. "https://test.salesforce.com/",
  100. "https://user.gini.net/",
  101. "https://www.douban.com/",
  102. "https://www.googleapis.com/",
  103. "https://www.linkedin.com/",
  104. "https://www.strava.com/oauth/",
  105. "https://www.wunderlist.com/oauth/",
  106. "https://api.patreon.com/",
  107. "https://sandbox.codeswholesale.com/oauth/token",
  108. "https://api.codeswholesale.com/oauth/token",
  109. }
  110. func RegisterBrokenAuthHeaderProvider(tokenURL string) {
  111. brokenAuthHeaderProviders = append(brokenAuthHeaderProviders, tokenURL)
  112. }
  113. // providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL
  114. // implements the OAuth2 spec correctly
  115. // See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
  116. // In summary:
  117. // - Reddit only accepts client secret in the Authorization header
  118. // - Dropbox accepts either it in URL param or Auth header, but not both.
  119. // - Google only accepts URL param (not spec compliant?), not Auth header
  120. // - Stripe only accepts client secret in Auth header with Bearer method, not Basic
  121. func providerAuthHeaderWorks(tokenURL string) bool {
  122. for _, s := range brokenAuthHeaderProviders {
  123. if strings.HasPrefix(tokenURL, s) {
  124. // Some sites fail to implement the OAuth2 spec fully.
  125. return false
  126. }
  127. }
  128. // Assume the provider implements the spec properly
  129. // otherwise. We can add more exceptions as they're
  130. // discovered. We will _not_ be adding configurable hooks
  131. // to this package to let users select server bugs.
  132. return true
  133. }
  134. func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error) {
  135. hc, err := ContextClient(ctx)
  136. if err != nil {
  137. return nil, err
  138. }
  139. v.Set("client_id", clientID)
  140. bustedAuth := !providerAuthHeaderWorks(tokenURL)
  141. if bustedAuth && clientSecret != "" {
  142. v.Set("client_secret", clientSecret)
  143. }
  144. req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode()))
  145. if err != nil {
  146. return nil, err
  147. }
  148. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  149. if !bustedAuth {
  150. req.SetBasicAuth(clientID, clientSecret)
  151. }
  152. r, err := hc.Do(req)
  153. if err != nil {
  154. return nil, err
  155. }
  156. defer r.Body.Close()
  157. body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
  158. if err != nil {
  159. return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
  160. }
  161. if code := r.StatusCode; code < 200 || code > 299 {
  162. return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", r.Status, body)
  163. }
  164. var token *Token
  165. content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
  166. switch content {
  167. case "application/x-www-form-urlencoded", "text/plain":
  168. vals, err := url.ParseQuery(string(body))
  169. if err != nil {
  170. return nil, err
  171. }
  172. token = &Token{
  173. AccessToken: vals.Get("access_token"),
  174. TokenType: vals.Get("token_type"),
  175. RefreshToken: vals.Get("refresh_token"),
  176. Raw: vals,
  177. }
  178. e := vals.Get("expires_in")
  179. if e == "" {
  180. // TODO(jbd): Facebook's OAuth2 implementation is broken and
  181. // returns expires_in field in expires. Remove the fallback to expires,
  182. // when Facebook fixes their implementation.
  183. e = vals.Get("expires")
  184. }
  185. expires, _ := strconv.Atoi(e)
  186. if expires != 0 {
  187. token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
  188. }
  189. default:
  190. var tj tokenJSON
  191. if err = json.Unmarshal(body, &tj); err != nil {
  192. return nil, err
  193. }
  194. token = &Token{
  195. AccessToken: tj.AccessToken,
  196. TokenType: tj.TokenType,
  197. RefreshToken: tj.RefreshToken,
  198. Expiry: tj.expiry(),
  199. Raw: make(map[string]interface{}),
  200. }
  201. json.Unmarshal(body, &token.Raw) // no error checks for optional fields
  202. }
  203. // Don't overwrite `RefreshToken` with an empty value
  204. // if this was a token refreshing request.
  205. if token.RefreshToken == "" {
  206. token.RefreshToken = v.Get("refresh_token")
  207. }
  208. return token, nil
  209. }