2021-09-08 18:04:56 +00:00
|
|
|
package application
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
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"
|
|
|
|
)
|
|
|
|
|
2021-12-26 13:11:11 +00:00
|
|
|
func (a *Application) redeemCallback(r *http.Request, states []string) (*Claims, error) {
|
2021-09-08 18:04:56 +00:00
|
|
|
state := r.URL.Query().Get("state")
|
2021-12-26 13:11:11 +00:00
|
|
|
if len(states) < 1 {
|
|
|
|
return nil, fmt.Errorf("no states")
|
|
|
|
}
|
|
|
|
found := false
|
|
|
|
for _, fstate := range states {
|
|
|
|
if fstate == state {
|
|
|
|
found = true
|
|
|
|
}
|
|
|
|
}
|
2022-09-07 07:53:07 +00:00
|
|
|
a.log.WithFields(log.Fields{
|
|
|
|
"states": states,
|
|
|
|
"expected": state,
|
|
|
|
"found": found,
|
|
|
|
}).Trace("tracing states")
|
2021-12-26 13:11:11 +00:00
|
|
|
if !found {
|
|
|
|
return nil, fmt.Errorf("invalid state")
|
2021-09-08 18:04:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
code := r.URL.Query().Get("code")
|
|
|
|
if code == "" {
|
|
|
|
return nil, fmt.Errorf("blank code")
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx := context.WithValue(r.Context(), oauth2.HTTPClient, a.httpClient)
|
|
|
|
// 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
|
|
|
|
}
|