2021-09-08 18:04:56 +00:00
|
|
|
package application
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2022-09-19 19:38:34 +00:00
|
|
|
"net/url"
|
2021-09-08 18:04:56 +00:00
|
|
|
|
2022-09-07 07:53:07 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2021-09-08 18:04:56 +00:00
|
|
|
"golang.org/x/oauth2"
|
|
|
|
)
|
|
|
|
|
2022-10-20 19:27:34 +00:00
|
|
|
func (a *Application) redeemCallback(savedState string, u *url.URL, c context.Context) (*Claims, error) {
|
2022-09-19 19:38:34 +00:00
|
|
|
state := u.Query().Get("state")
|
2022-09-07 07:53:07 +00:00
|
|
|
a.log.WithFields(log.Fields{
|
2022-10-20 19:27:34 +00:00
|
|
|
"states": savedState,
|
2022-09-07 07:53:07 +00:00
|
|
|
"expected": state,
|
|
|
|
}).Trace("tracing states")
|
2022-10-20 19:27:34 +00:00
|
|
|
if savedState != state {
|
2021-12-26 13:11:11 +00:00
|
|
|
return nil, fmt.Errorf("invalid state")
|
2021-09-08 18:04:56 +00:00
|
|
|
}
|
|
|
|
|
2022-09-19 19:38:34 +00:00
|
|
|
code := u.Query().Get("code")
|
2021-09-08 18:04:56 +00:00
|
|
|
if code == "" {
|
|
|
|
return nil, fmt.Errorf("blank code")
|
|
|
|
}
|
|
|
|
|
2022-09-19 19:38:34 +00:00
|
|
|
ctx := context.WithValue(c, oauth2.HTTPClient, a.httpClient)
|
2021-09-08 18:04:56 +00:00
|
|
|
// Verify state and errors.
|
|
|
|
oauth2Token, err := a.oauthConfig.Exchange(ctx, code)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extract the ID Token from OAuth2 token.
|
|
|
|
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("missing id_token")
|
|
|
|
}
|
|
|
|
|
|
|
|
a.log.WithField("id_token", rawIDToken).Trace("id_token")
|
|
|
|
|
|
|
|
// Parse and verify ID Token payload.
|
|
|
|
idToken, err := a.tokenVerifier.Verify(ctx, rawIDToken)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extract custom claims
|
|
|
|
var claims *Claims
|
|
|
|
if err := idToken.Claims(&claims); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-12-12 16:58:19 +00:00
|
|
|
claims.RawToken = rawIDToken
|
2021-09-08 18:04:56 +00:00
|
|
|
return claims, nil
|
|
|
|
}
|