@@ -3,10 +3,13 @@ package providers
33import (
44 "context"
55 "fmt"
6+ "net/http"
67 "time"
78
89 oidc "github.com/coreos/go-oidc"
910 "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
11+ "github.com/pusher/oauth2_proxy/pkg/requests"
12+
1013 "golang.org/x/oauth2"
1114)
1215
@@ -117,8 +120,31 @@ func (p *OIDCProvider) createSessionState(ctx context.Context, token *oauth2.Tok
117120 }
118121
119122 if claims.Email == "" {
120− // TODO: Try getting email from /userinfo before falling back to Subject
121− claims.Email = claims.Subject
123+ if p.ProfileURL.String() == "" {
124+ return nil, fmt.Errorf("id_token did not contain an email")
125+ }
126+
127+ // If the userinfo endpoint profileURL is defined, then there is a chance the userinfo
128+ // contents at the profileURL contains the email.
129+ // Make a query to the userinfo endpoint, and attempt to locate the email from there.
130+
131+ req, err := http.NewRequest("GET", p.ProfileURL.String(), nil)
132+ if err != nil {
133+ return nil, err
134+ }
135+ req.Header = getOIDCHeader(token.AccessToken)
136+
137+ respJSON, err := requests.Request(req)
138+ if err != nil {
139+ return nil, err
140+ }
141+
142+ email, err := respJSON.Get("email").String()
143+ if err != nil {
144+ return nil, fmt.Errorf("Neither id_token nor userinfo endpoint contained an email")
145+ }
146+
147+ claims.Email = email
122148 }
123149 if !p.AllowUnverifiedEmail && claims.Verified != nil && !*claims.Verified {
124150 return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email)
@@ -145,3 +171,10 @@ func (p *OIDCProvider) ValidateSessionState(s *sessions.SessionState) bool {
145171
146172 return true
147173}
174+
175+func getOIDCHeader(accessToken string) http.Header {
176+ header := make(http.Header)
177+ header.Set("Accept", "application/json")
178+ header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
179+ return header
180+}