Skip to content

Commit 6057702

Browse files
committed
oauth2: return error, error_description, and error_uri when error field is present in token response
1 parent bf48bf1 commit 6057702

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

internal/token.go

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,15 @@ type Token struct {
5757
}
5858

5959
// tokenJSON is the struct representing the HTTP response from OAuth2
60-
// providers returning a token in JSON form.
60+
// providers returning a token or error in JSON form.
6161
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
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
66+
Error string `json:"error"`
67+
ErrorDescription string `json:"error_description"`
68+
ErrorURI string `json:"error_uri"`
6669
}
6770

6871
func (e *tokenJSON) expiry() (t time.Time) {
@@ -253,6 +256,13 @@ func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) {
253256
if err != nil {
254257
return nil, err
255258
}
259+
if tokenError := vals.Get("error"); tokenError != "" {
260+
return nil, &TokenError{
261+
Err: tokenError,
262+
ErrorDescription: vals.Get("error_description"),
263+
ErrorURI: vals.Get("error_uri"),
264+
}
265+
}
256266
token = &Token{
257267
AccessToken: vals.Get("access_token"),
258268
TokenType: vals.Get("token_type"),
@@ -269,6 +279,13 @@ func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) {
269279
if err = json.Unmarshal(body, &tj); err != nil {
270280
return nil, err
271281
}
282+
if tj.Error != "" {
283+
return nil, &TokenError{
284+
Err: tj.Error,
285+
ErrorDescription: tj.ErrorDescription,
286+
ErrorURI: tj.ErrorURI,
287+
}
288+
}
272289
token = &Token{
273290
AccessToken: tj.AccessToken,
274291
TokenType: tj.TokenType,
@@ -292,3 +309,13 @@ type RetrieveError struct {
292309
func (r *RetrieveError) Error() string {
293310
return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body)
294311
}
312+
313+
type TokenError struct {
314+
Err string
315+
ErrorDescription string
316+
ErrorURI string
317+
}
318+
319+
func (t *TokenError) Error() string {
320+
return fmt.Sprintf("oauth2: error in token fetch repsonse: %s\nerror_description: %s\nerror_uri: %s", t.Err, t.ErrorDescription, t.ErrorURI)
321+
}

0 commit comments

Comments
 (0)