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.
23 "golang.org/x/net/context/ctxhttp"
26 // Token represents the credentials used to authorize
27 // the requests to access protected resources on the OAuth 2.0
28 // provider's backend.
30 // This type is a mirror of oauth2.Token and exists to break
31 // an otherwise-circular dependency. Other internal packages
32 // should convert this Token into an oauth2.Token before use.
34 // AccessToken is the token that authorizes and authenticates
38 // TokenType is the type of token.
39 // The Type method returns either this or "Bearer", the default.
42 // RefreshToken is a token that's used by the application
43 // (as opposed to the user) to refresh the access token
47 // Expiry is the optional expiration time of the access token.
49 // If zero, TokenSource implementations will reuse the same
50 // token forever and RefreshToken or equivalent
51 // mechanisms for that TokenSource will not be used.
54 // Raw optionally contains extra metadata from the server
55 // when updating a token.
59 // tokenJSON is the struct representing the HTTP response from OAuth2
60 // providers returning a token in JSON form.
61 type tokenJSON struct {
62 AccessToken string `json:"access_token"`
63 TokenType string `json:"token_type"`
64 RefreshToken string `json:"refresh_token"`
65 ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number
68 func (e *tokenJSON) expiry() (t time.Time) {
69 if v := e.ExpiresIn; v != 0 {
70 return time.Now().Add(time.Duration(v) * time.Second)
75 type expirationTime int32
77 func (e *expirationTime) UnmarshalJSON(b []byte) error {
78 if len(b) == 0 || string(b) == "null" {
82 err := json.Unmarshal(b, &n)
90 if i > math.MaxInt32 {
93 *e = expirationTime(i)
97 // RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op.
99 // Deprecated: this function no longer does anything. Caller code that
100 // wants to avoid potential extra HTTP requests made during
101 // auto-probing of the provider's auth style should set
102 // Endpoint.AuthStyle.
103 func RegisterBrokenAuthHeaderProvider(tokenURL string) {}
105 // AuthStyle is a copy of the golang.org/x/oauth2 package's AuthStyle type.
109 AuthStyleUnknown AuthStyle = 0
110 AuthStyleInParams AuthStyle = 1
111 AuthStyleInHeader AuthStyle = 2
114 // authStyleCache is the set of tokenURLs we've successfully used via
115 // RetrieveToken and which style auth we ended up using.
116 // It's called a cache, but it doesn't (yet?) shrink. It's expected that
117 // the set of OAuth2 servers a program contacts over time is fixed and
119 var authStyleCache struct {
121 m map[string]AuthStyle // keyed by tokenURL
124 // ResetAuthCache resets the global authentication style cache used
125 // for AuthStyleUnknown token requests.
126 func ResetAuthCache() {
127 authStyleCache.Lock()
128 defer authStyleCache.Unlock()
129 authStyleCache.m = nil
132 // lookupAuthStyle reports which auth style we last used with tokenURL
133 // when calling RetrieveToken and whether we have ever done so.
134 func lookupAuthStyle(tokenURL string) (style AuthStyle, ok bool) {
135 authStyleCache.Lock()
136 defer authStyleCache.Unlock()
137 style, ok = authStyleCache.m[tokenURL]
141 // setAuthStyle adds an entry to authStyleCache, documented above.
142 func setAuthStyle(tokenURL string, v AuthStyle) {
143 authStyleCache.Lock()
144 defer authStyleCache.Unlock()
145 if authStyleCache.m == nil {
146 authStyleCache.m = make(map[string]AuthStyle)
148 authStyleCache.m[tokenURL] = v
151 // newTokenRequest returns a new *http.Request to retrieve a new token
152 // from tokenURL using the provided clientID, clientSecret, and POST
155 // inParams is whether the clientID & clientSecret should be encoded
156 // as the POST body. An 'inParams' value of true means to send it in
157 // the POST body (along with any values in v); false means to send it
158 // in the Authorization header.
159 func newTokenRequest(tokenURL, clientID, clientSecret string, v url.Values, authStyle AuthStyle) (*http.Request, error) {
160 if authStyle == AuthStyleInParams {
161 v = cloneURLValues(v)
163 v.Set("client_id", clientID)
165 if clientSecret != "" {
166 v.Set("client_secret", clientSecret)
169 req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode()))
173 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
174 if authStyle == AuthStyleInHeader {
175 req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret))
180 func cloneURLValues(v url.Values) url.Values {
181 v2 := make(url.Values, len(v))
182 for k, vv := range v {
183 v2[k] = append([]string(nil), vv...)
188 func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values, authStyle AuthStyle) (*Token, error) {
189 needsAuthStyleProbe := authStyle == 0
190 if needsAuthStyleProbe {
191 if style, ok := lookupAuthStyle(tokenURL); ok {
193 needsAuthStyleProbe = false
195 authStyle = AuthStyleInHeader // the first way we'll try
198 req, err := newTokenRequest(tokenURL, clientID, clientSecret, v, authStyle)
202 token, err := doTokenRoundTrip(ctx, req)
203 if err != nil && needsAuthStyleProbe {
204 // If we get an error, assume the server wants the
205 // clientID & clientSecret in a different form.
206 // See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
208 // - Reddit only accepts client secret in the Authorization header
209 // - Dropbox accepts either it in URL param or Auth header, but not both.
210 // - Google only accepts URL param (not spec compliant?), not Auth header
211 // - Stripe only accepts client secret in Auth header with Bearer method, not Basic
213 // We used to maintain a big table in this code of all the sites and which way
214 // they went, but maintaining it didn't scale & got annoying.
215 // So just try both ways.
216 authStyle = AuthStyleInParams // the second way we'll try
217 req, _ = newTokenRequest(tokenURL, clientID, clientSecret, v, authStyle)
218 token, err = doTokenRoundTrip(ctx, req)
220 if needsAuthStyleProbe && err == nil {
221 setAuthStyle(tokenURL, authStyle)
223 // Don't overwrite `RefreshToken` with an empty value
224 // if this was a token refreshing request.
225 if token != nil && token.RefreshToken == "" {
226 token.RefreshToken = v.Get("refresh_token")
231 func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) {
232 r, err := ctxhttp.Do(ctx, ContextClient(ctx), req)
236 body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
239 return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
241 if code := r.StatusCode; code < 200 || code > 299 {
242 return nil, &RetrieveError{
249 content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
251 case "application/x-www-form-urlencoded", "text/plain":
252 vals, err := url.ParseQuery(string(body))
257 AccessToken: vals.Get("access_token"),
258 TokenType: vals.Get("token_type"),
259 RefreshToken: vals.Get("refresh_token"),
262 e := vals.Get("expires_in")
263 expires, _ := strconv.Atoi(e)
265 token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
269 if err = json.Unmarshal(body, &tj); err != nil {
273 AccessToken: tj.AccessToken,
274 TokenType: tj.TokenType,
275 RefreshToken: tj.RefreshToken,
277 Raw: make(map[string]interface{}),
279 json.Unmarshal(body, &token.Raw) // no error checks for optional fields
281 if token.AccessToken == "" {
282 return nil, errors.New("oauth2: server response missing access_token")
287 type RetrieveError struct {
288 Response *http.Response
292 func (r *RetrieveError) Error() string {
293 return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body)