-
Notifications
You must be signed in to change notification settings - Fork 283
/
userinfo.go
73 lines (60 loc) · 1.98 KB
/
userinfo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package oidc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
// getUserInfo gets the user info for OIDC. We wrap the underlying call because AWS Cognito chose to violate the spec
// and return data in an invalid format. By using our own custom http client, we're able to modify the response to
// make it compliant, and then the rest of the library works as expected.
func getUserInfo(ctx context.Context, provider *oidc.Provider, tokenSource oauth2.TokenSource) (*oidc.UserInfo, error) {
originalClient := http.DefaultClient
if c, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok {
originalClient = c
}
client := new(http.Client)
*client = *originalClient
client.Transport = &userInfoRoundTripper{underlying: client.Transport}
ctx = context.WithValue(ctx, oauth2.HTTPClient, client)
return provider.UserInfo(ctx, tokenSource)
}
type userInfoRoundTripper struct {
underlying http.RoundTripper
}
func (transport *userInfoRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
underlying := transport.underlying
if underlying == nil {
underlying = http.DefaultTransport
}
res, err := underlying.RoundTrip(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var userInfo map[string]interface{}
if err := json.Unmarshal(bs, &userInfo); err == nil {
// AWS Cognito returns email_verified as a string, so we'll make it a bool
if ev, ok := userInfo["email_verified"]; ok {
userInfo["email_verified"], _ = strconv.ParseBool(fmt.Sprint(ev))
}
// Some providers (ping) have a "mail" claim instead of "email"
email, mail := userInfo["email"], userInfo["mail"]
if email == nil && mail != nil && strings.Contains(fmt.Sprint(mail), "@") {
userInfo["email"] = mail
}
bs, _ = json.Marshal(userInfo)
}
res.Body = ioutil.NopCloser(bytes.NewReader(bs))
return res, nil
}