1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2025-01-10 04:18:14 +02:00
oauth2-proxy/providers/oidc.go

265 lines
6.8 KiB
Go
Raw Normal View History

package providers
import (
"context"
2020-11-27 05:00:30 +02:00
"errors"
"fmt"
"net/url"
2020-11-30 00:58:01 +02:00
"reflect"
"time"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
2020-11-27 05:00:30 +02:00
"golang.org/x/oauth2"
)
// OIDCProvider represents an OIDC based Identity Provider
type OIDCProvider struct {
*ProviderData
SkipNonce bool
}
// NewOIDCProvider initiates a new OIDCProvider
func NewOIDCProvider(p *ProviderData) *OIDCProvider {
2017-10-08 06:40:36 +02:00
p.ProviderName = "OpenID Connect"
return &OIDCProvider{
ProviderData: p,
SkipNonce: true,
}
}
var _ Provider = (*OIDCProvider)(nil)
// GetLoginURL makes the LoginURL with optional nonce support
func (p *OIDCProvider) GetLoginURL(redirectURI, state, nonce string) string {
extraParams := url.Values{}
if !p.SkipNonce {
extraParams.Add("nonce", nonce)
}
loginURL := makeLoginURL(p.Data(), redirectURI, state, extraParams)
return loginURL.String()
}
// Redeem exchanges the OAuth2 authentication token for an ID token
2020-11-27 05:00:30 +02:00
func (p *OIDCProvider) Redeem(ctx context.Context, redirectURL, code string) (*sessions.SessionState, error) {
clientSecret, err := p.GetClientSecret()
if err != nil {
2020-11-27 05:00:30 +02:00
return nil, err
}
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 failed: %v", err)
}
2020-11-27 05:00:30 +02:00
return p.createSession(ctx, token, false)
}
2020-12-02 03:50:27 +02:00
// EnrichSession is called after Redeem to allow providers to enrich session fields
2020-11-27 05:00:30 +02:00
// such as User, Email, Groups with provider specific API calls.
func (p *OIDCProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {
if p.ProfileURL.String() == "" {
if s.Email == "" {
return errors.New("id_token did not contain an email and profileURL is not defined")
}
return nil
}
// Try to get missing emails or groups from a profileURL
2020-11-30 00:58:01 +02:00
if s.Email == "" || s.Groups == nil {
2020-12-02 03:50:27 +02:00
err := p.enrichFromProfileURL(ctx, s)
2020-11-27 05:00:30 +02:00
if err != nil {
logger.Errorf("Warning: Profile URL request failed: %v", err)
}
}
// If a mandatory email wasn't set, error at this point.
if s.Email == "" {
return errors.New("neither the id_token nor the profileURL set an email")
}
2020-11-27 05:00:30 +02:00
return nil
}
2020-12-02 03:50:27 +02:00
// enrichFromProfileURL enriches a session's Email & Groups via the JSON response of
2020-11-27 05:00:30 +02:00
// an OIDC profile URL
2020-12-02 03:50:27 +02:00
func (p *OIDCProvider) enrichFromProfileURL(ctx context.Context, s *sessions.SessionState) error {
2020-11-27 05:00:30 +02:00
respJSON, err := requests.New(p.ProfileURL.String()).
WithContext(ctx).
WithHeaders(makeOIDCHeader(s.AccessToken)).
Do().
UnmarshalJSON()
if err != nil {
2020-11-27 05:00:30 +02:00
return err
}
email, err := respJSON.Get(p.EmailClaim).String()
if err == nil && s.Email == "" {
s.Email = email
}
2020-12-02 03:50:27 +02:00
if len(s.Groups) > 0 {
return nil
}
for _, group := range coerceArray(respJSON, p.GroupsClaim) {
formatted, err := formatGroup(group)
if err != nil {
logger.Errorf("Warning: unable to format group of type %s with error %s",
reflect.TypeOf(group), err)
continue
2020-11-27 05:00:30 +02:00
}
2020-12-02 03:50:27 +02:00
s.Groups = append(s.Groups, formatted)
}
2020-11-27 05:00:30 +02:00
return nil
}
2020-12-02 03:50:27 +02:00
// ValidateSession checks that the session's IDToken is still valid
2020-11-27 05:00:30 +02:00
func (p *OIDCProvider) ValidateSession(ctx context.Context, s *sessions.SessionState) bool {
idToken, err := p.Verifier.Verify(ctx, s.IDToken)
if err != nil {
logger.Errorf("id_token verification failed: %v", err)
return false
}
if p.SkipNonce {
return true
}
err = p.checkNonce(s, idToken)
if err != nil {
logger.Errorf("nonce verification failed: %v", err)
return false
}
return true
}
// RefreshSession uses the RefreshToken to fetch new Access and ID Tokens
func (p *OIDCProvider) RefreshSession(ctx context.Context, s *sessions.SessionState) (bool, error) {
if s == nil || s.RefreshToken == "" {
return false, nil
}
err := p.redeemRefreshToken(ctx, s)
if err != nil {
return false, fmt.Errorf("unable to redeem refresh token: %v", err)
}
return true, nil
}
2020-11-27 05:00:30 +02:00
// redeemRefreshToken uses a RefreshToken with the RedeemURL to refresh the
// Access Token and (probably) the ID Token.
func (p *OIDCProvider) redeemRefreshToken(ctx context.Context, s *sessions.SessionState) error {
clientSecret, err := p.GetClientSecret()
if err != nil {
2020-11-27 05:00:30 +02:00
return err
}
c := oauth2.Config{
ClientID: p.ClientID,
ClientSecret: clientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: p.RedeemURL.String(),
},
}
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)
}
2020-11-27 05:00:30 +02:00
newSession, err := p.createSession(ctx, token, true)
if err != nil {
return fmt.Errorf("unable create new session state from response: %v", err)
}
2020-11-27 05:00:30 +02:00
// 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.Groups = newSession.Groups
s.PreferredUsername = newSession.PreferredUsername
}
s.AccessToken = newSession.AccessToken
s.RefreshToken = newSession.RefreshToken
2019-05-07 16:32:46 +02:00
s.CreatedAt = newSession.CreatedAt
s.ExpiresOn = newSession.ExpiresOn
2020-11-27 05:00:30 +02:00
return nil
}
2020-11-27 05:00:30 +02:00
// CreateSessionFromToken converts Bearer IDTokens into sessions
func (p *OIDCProvider) CreateSessionFromToken(ctx context.Context, token string) (*sessions.SessionState, error) {
idToken, err := p.Verifier.Verify(ctx, token)
if err != nil {
return nil, err
}
2020-11-27 05:00:30 +02:00
ss, err := p.buildSessionFromClaims(idToken)
if err != nil {
return nil, err
}
2020-11-27 05:00:30 +02:00
// Allow empty Email in Bearer case since we can't hit the ProfileURL
if ss.Email == "" {
ss.Email = ss.User
}
2020-11-27 05:00:30 +02:00
ss.AccessToken = token
ss.IDToken = token
ss.RefreshToken = ""
2021-03-07 01:33:40 +02:00
ss.CreatedAtNow()
ss.SetExpiresOn(idToken.Expiry)
2020-11-27 05:00:30 +02:00
return ss, nil
}
2020-11-27 05:00:30 +02:00
// createSession takes an oauth2.Token and creates a SessionState from it.
// It alters behavior if called from Redeem vs Refresh
func (p *OIDCProvider) createSession(ctx context.Context, token *oauth2.Token, refresh bool) (*sessions.SessionState, error) {
idToken, err := p.verifyIDToken(ctx, token)
if err != nil {
2020-12-01 22:01:42 +02:00
switch err {
case ErrMissingIDToken:
// IDToken is mandatory in Redeem but optional in Refresh
if !refresh {
return nil, errors.New("token response did not contain an id_token")
}
default:
return nil, fmt.Errorf("could not verify id_token: %v", err)
}
}
2020-11-27 05:00:30 +02:00
ss, err := p.buildSessionFromClaims(idToken)
if err != nil {
return nil, err
}
2020-11-27 05:00:30 +02:00
ss.AccessToken = token.AccessToken
ss.RefreshToken = token.RefreshToken
ss.IDToken = getIDToken(token)
2021-03-07 01:33:40 +02:00
ss.CreatedAtNow()
ss.SetExpiresOn(token.Expiry)
2020-11-27 05:00:30 +02:00
return ss, nil
}