forked from oauth2-proxy/oauth2-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oidc.go
241 lines (197 loc) · 6.54 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package providers
import (
"context"
"fmt"
"net/http"
"strings"
"time"
oidc "github.com/coreos/go-oidc"
"golang.org/x/oauth2"
"github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/requests"
)
// OIDCProvider represents an OIDC based Identity Provider
type OIDCProvider struct {
*ProviderData
Verifier *oidc.IDTokenVerifier
AllowUnverifiedEmail bool
}
// NewOIDCProvider initiates a new OIDCProvider
func NewOIDCProvider(p *ProviderData) *OIDCProvider {
p.ProviderName = "OpenID Connect"
return &OIDCProvider{ProviderData: p}
}
// Redeem exchanges the OAuth2 authentication token for an ID token
func (p *OIDCProvider) Redeem(redirectURL, code string) (s *sessions.SessionState, err error) {
clientSecret, err := p.GetClientSecret()
if err != nil {
return
}
ctx := context.Background()
c := oauth2.Config{
ClientID: p.ClientID,
ClientSecret: clientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: p.RedeemURL.String(),
},
RedirectURL: redirectURL,
}
token, err := c.Exchange(ctx, code)
if err != nil {
return nil, fmt.Errorf("token exchange: %v", err)
}
// in the initial exchange the id token is mandatory
idToken, err := p.findVerifiedIDToken(ctx, token)
if err != nil {
return nil, fmt.Errorf("could not verify id_token: %v", err)
} else if idToken == nil {
return nil, fmt.Errorf("token response did not contain an id_token")
}
s, err = p.createSessionState(token, idToken)
if err != nil {
return nil, fmt.Errorf("unable to update session: %v", err)
}
return
}
// RefreshSessionIfNeeded checks if the session has expired and uses the
// RefreshToken to fetch a new Access Token (and optional ID token) if required
func (p *OIDCProvider) RefreshSessionIfNeeded(s *sessions.SessionState) (bool, error) {
if s == nil || s.ExpiresOn.After(time.Now()) || s.RefreshToken == "" {
return false, nil
}
err := p.redeemRefreshToken(s)
if err != nil {
return false, fmt.Errorf("unable to redeem refresh token: %v", err)
}
fmt.Printf("refreshed access token %s (expired on %s)\n", s, s.ExpiresOn)
return true, nil
}
func (p *OIDCProvider) redeemRefreshToken(s *sessions.SessionState) (err error) {
clientSecret, err := p.GetClientSecret()
if err != nil {
return
}
c := oauth2.Config{
ClientID: p.ClientID,
ClientSecret: clientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: p.RedeemURL.String(),
},
}
ctx := context.Background()
t := &oauth2.Token{
RefreshToken: s.RefreshToken,
Expiry: time.Now().Add(-time.Hour),
}
token, err := c.TokenSource(ctx, t).Token()
if err != nil {
return fmt.Errorf("failed to get token: %v", err)
}
// in the token refresh response the id_token is optional
idToken, err := p.findVerifiedIDToken(ctx, token)
if err != nil {
return fmt.Errorf("unable to extract id_token from response: %v", err)
}
newSession, err := p.createSessionState(token, idToken)
if err != nil {
return fmt.Errorf("unable create new session state from response: %v", err)
}
// It's possible that if the refresh token isn't in the token response the session will not contain an id token
// if it doesn't it's probably better to retain the old one
if newSession.IDToken != "" {
s.IDToken = newSession.IDToken
s.Email = newSession.Email
s.User = newSession.User
s.PreferredUsername = newSession.PreferredUsername
}
s.AccessToken = newSession.AccessToken
s.RefreshToken = newSession.RefreshToken
s.CreatedAt = newSession.CreatedAt
s.ExpiresOn = newSession.ExpiresOn
return
}
func (p *OIDCProvider) findVerifiedIDToken(ctx context.Context, token *oauth2.Token) (*oidc.IDToken, error) {
getIDToken := func() (string, bool) {
rawIDToken, _ := token.Extra("id_token").(string)
return rawIDToken, len(strings.TrimSpace(rawIDToken)) > 0
}
if rawIDToken, present := getIDToken(); present {
verifiedIDToken, err := p.Verifier.Verify(ctx, rawIDToken)
return verifiedIDToken, err
}
return nil, nil
}
func (p *OIDCProvider) createSessionState(token *oauth2.Token, idToken *oidc.IDToken) (*sessions.SessionState, error) {
newSession := &sessions.SessionState{}
if idToken != nil {
claims, err := findClaimsFromIDToken(idToken, token.AccessToken, p.ProfileURL.String())
if err != nil {
return nil, fmt.Errorf("couldn't extract claims from id_token (%e)", err)
}
if claims != nil {
if !p.AllowUnverifiedEmail && claims.Verified != nil && !*claims.Verified {
return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email)
}
newSession.IDToken = token.Extra("id_token").(string)
newSession.Email = claims.Email
newSession.User = claims.Subject
newSession.PreferredUsername = claims.PreferredUsername
}
}
newSession.AccessToken = token.AccessToken
newSession.RefreshToken = token.RefreshToken
newSession.CreatedAt = time.Now()
newSession.ExpiresOn = token.Expiry
return newSession, nil
}
// ValidateSessionState checks that the session's IDToken is still valid
func (p *OIDCProvider) ValidateSessionState(s *sessions.SessionState) bool {
ctx := context.Background()
_, err := p.Verifier.Verify(ctx, s.IDToken)
if err != nil {
return false
}
return true
}
func getOIDCHeader(accessToken string) http.Header {
header := make(http.Header)
header.Set("Accept", "application/json")
header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
return header
}
func findClaimsFromIDToken(idToken *oidc.IDToken, accessToken string, profileURL string) (*OIDCClaims, error) {
// Extract custom claims.
claims := &OIDCClaims{}
if err := idToken.Claims(claims); err != nil {
return nil, fmt.Errorf("failed to parse id_token claims: %v", err)
}
if claims.Email == "" {
if profileURL == "" {
return nil, fmt.Errorf("id_token did not contain an email")
}
// If the userinfo endpoint profileURL is defined, then there is a chance the userinfo
// contents at the profileURL contains the email.
// Make a query to the userinfo endpoint, and attempt to locate the email from there.
req, err := http.NewRequest("GET", profileURL, nil)
if err != nil {
return nil, err
}
req.Header = getOIDCHeader(accessToken)
respJSON, err := requests.Request(req)
if err != nil {
return nil, err
}
email, err := respJSON.Get("email").String()
if err != nil {
return nil, fmt.Errorf("neither id_token nor userinfo endpoint contained an email")
}
claims.Email = email
}
return claims, nil
}
type OIDCClaims struct {
Subject string `json:"sub"`
Email string `json:"email"`
Verified *bool `json:"email_verified"`
PreferredUsername string `json:"preferred_username"`
}