/
oidc.go
75 lines (62 loc) · 1.82 KB
/
oidc.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
74
75
// Package auth provides a simple wrapper around values needed for the openidconnect package
package auth
import (
"context"
"errors"
"github.com/coreos/go-oidc/v3/oidc"
"go.hollow.sh/toolbox/ginjwt"
"golang.org/x/oauth2"
"gopkg.in/square/go-jose.v2/jwt"
)
// OIDCProviderConfig is used to configure the openidconnect object from the openidconnect package
// github.com/markbates/goth/providers/openidConnect
type OIDCProviderConfig struct {
OIDCClientKey string
OIDCClientSecret string
OIDCCallbackURL string
OIDCDiscoveryURL string
OIDCProviderName string
OIDCScopes []string
}
// OIDCUserInfo provides basic user info from OIDC
type OIDCUserInfo struct {
Name string `json:"name"`
Email string `json:"email"`
Sub string `json:"sub"`
}
// UserInfoFromJWT tries to retrieve the user info (id token claims) using the given jwt token. It will
// use the oidc provider matching the issuer in the access token
func UserInfoFromJWT(ctx context.Context, rawToken string, oidcConfigs []ginjwt.AuthConfig) (*OIDCUserInfo, error) {
var userInfo *oidc.UserInfo
accessToken, err := jwt.ParseSigned(rawToken)
if err != nil {
return nil, err
}
tok := jwt.Claims{}
if err := accessToken.UnsafeClaimsWithoutVerification(&tok); err != nil {
return nil, err
}
for _, ac := range oidcConfigs {
if ac.Issuer != tok.Issuer {
continue
}
provider, err := oidc.NewProvider(ctx, ac.Issuer)
if err != nil {
return nil, err
}
userInfo, err = provider.UserInfo(ctx, oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: rawToken,
}))
if err != nil {
return nil, err
}
}
if userInfo == nil {
return nil, errors.New("didn't find matching oidc issuer") //nolint:goerr113
}
userClaims := OIDCUserInfo{}
if err := userInfo.Claims(&userClaims); err != nil {
return nil, err
}
return &userClaims, nil
}