Debian Codegraph @

pkg/client/rp/relying_party.go

raw
1 package rp
2
3 import (
4 "context"
5 "encoding/base64"
6 "errors"
7 "fmt"
8 "log/slog"
9 "net/http"
10 "net/url"
11 "slices"
12 "time"
13
14 "github.com/go-jose/go-jose/v4"
15 "github.com/google/uuid"
16 "golang.org/x/oauth2"
17 "golang.org/x/oauth2/clientcredentials"
18
19 "github.com/zitadel/oidc/v3/pkg/client"
20 httphelper "github.com/zitadel/oidc/v3/pkg/http"
21 "github.com/zitadel/oidc/v3/pkg/oidc"
22 )
23
24 const (
25 pkceDisabled pkceState = iota
26 pkceEnabled
27 pkceFromDiscovery
28
29 idTokenKey = "id_token"
30 stateParam = "state"
31 pkceCode = "pkce"
32 )
33
34 var (
35 ErrUserInfoSubNotMatching = errors.New("sub from userinfo does not match the sub from the id_token")
36 ErrInvalidOption = errors.New("invalid relying party option")
37 )
38
39 type pkceState uint8
40
41 // RelyingParty declares the minimal interface for oidc clients
42 type RelyingParty interface {
43 // OAuthConfig returns the oauth2 Config
44 OAuthConfig() *oauth2.Config
45
46 // Issuer returns the issuer of the oidc config
47 Issuer() string
48
49 // IsPKCE returns if authorization is done using `Authorization Code Flow with Proof Key for Code Exchange (PKCE)`
50 IsPKCE() bool
51
52 // CookieHandler returns a http cookie handler used for various state transfer cookies
53 CookieHandler() *httphelper.CookieHandler
54
55 // HttpClient returns an http client used for calls to the openid provider, e.g. calling token endpoint
56 HttpClient() *http.Client
57
58 // IsOAuth2Only specifies whether relaying party handles only oauth2 or oidc calls
59 IsOAuth2Only() bool
60
61 // Signer is used if the relaying party uses the JWT Profile
62 Signer() jose.Signer
63
64 // GetEndSessionEndpoint returns the endpoint to sign out on a IDP
65 GetEndSessionEndpoint() string
66
67 // GetRevokeEndpoint returns the endpoint to revoke a specific token
68 GetRevokeEndpoint() string
69
70 // UserinfoEndpoint returns the userinfo
71 UserinfoEndpoint() string
72
73 // GetDeviceAuthorizationEndpoint returns the endpoint which can
74 // be used to start a DeviceAuthorization flow.
75 GetDeviceAuthorizationEndpoint() string
76
77 // IDTokenVerifier returns the verifier used for oidc id_token verification
78 IDTokenVerifier() *IDTokenVerifier
79
80 // ErrorHandler returns the handler used for callback errors
81 ErrorHandler() func(http.ResponseWriter, *http.Request, string, string, string)
82
83 // Logger returns the logger configured with [WithLogger], or [slog.Default] if none was set.
84 // Deprecated: configure logging with [slog.SetDefault].
85 Logger(context.Context) (logger *slog.Logger, ok bool)
86 }
87
88 type HasUnauthorizedHandler interface {
89 // UnauthorizedHandler returns the handler used for unauthorized errors
90 UnauthorizedHandler() func(w http.ResponseWriter, r *http.Request, desc string, state string)
91 }
92
93 type (
94 ErrorHandler func(w http.ResponseWriter, r *http.Request, errorType string, errorDesc string, state string)
95 UnauthorizedHandler func(w http.ResponseWriter, r *http.Request, desc string, state string)
96 )
97
98 var DefaultErrorHandler ErrorHandler = func(w http.ResponseWriter, r *http.Request, errorType string, errorDesc string, state string) {
99 http.Error(w, errorType+": "+errorDesc, http.StatusInternalServerError)
100 }
101
102 var DefaultUnauthorizedHandler UnauthorizedHandler = func(w http.ResponseWriter, r *http.Request, desc string, state string) {
103 http.Error(w, desc, http.StatusUnauthorized)
104 }
105
106 type relyingParty struct {
107 issuer string
108 DiscoveryEndpoint string
109 endpoints Endpoints
110 oauthConfig *oauth2.Config
111 oauth2Only bool
112 pkce pkceState
113 useSigningAlgsFromDiscovery bool
114
115 httpClient *http.Client
116 cookieHandler *httphelper.CookieHandler
117
118 oauthAuthStyle oauth2.AuthStyle
119
120 errorHandler func(http.ResponseWriter, *http.Request, string, string, string)
121 unauthorizedHandler func(http.ResponseWriter, *http.Request, string, string)
122 idTokenVerifier *IDTokenVerifier
123 verifierOpts []VerifierOption
124 signer jose.Signer
125 keyBinding *keyBinding
126 logger *slog.Logger
127 }
128
129 func (rp *relyingParty) OAuthConfig() *oauth2.Config {
130 return rp.oauthConfig
131 }
132
133 func (rp *relyingParty) Issuer() string {
134 return rp.issuer
135 }
136
137 func (rp *relyingParty) IsPKCE() bool {
138 return rp.pkce == pkceEnabled
139 }
140
141 func (rp *relyingParty) CookieHandler() *httphelper.CookieHandler {
142 return rp.cookieHandler
143 }
144
145 func (rp *relyingParty) HttpClient() *http.Client {
146 return rp.httpClient
147 }
148
149 func (rp *relyingParty) IsOAuth2Only() bool {
150 return rp.oauth2Only
151 }
152
153 func (rp *relyingParty) Signer() jose.Signer {
154 return rp.signer
155 }
156
157 func (rp *relyingParty) UserinfoEndpoint() string {
158 return rp.endpoints.UserinfoURL
159 }
160
161 func (rp *relyingParty) GetDeviceAuthorizationEndpoint() string {
162 return rp.endpoints.DeviceAuthorizationURL
163 }
164
165 func (rp *relyingParty) GetEndSessionEndpoint() string {
166 return rp.endpoints.EndSessionURL
167 }
168
169 func (rp *relyingParty) GetRevokeEndpoint() string {
170 return rp.endpoints.RevokeURL
171 }
172
173 func (rp *relyingParty) IDTokenVerifier() *IDTokenVerifier {
174 if rp.idTokenVerifier == nil {
175 rp.idTokenVerifier = NewIDTokenVerifier(rp.issuer, rp.oauthConfig.ClientID, NewRemoteKeySet(rp.httpClient, rp.endpoints.JKWsURL), rp.verifierOpts...)
176 }
177 return rp.idTokenVerifier
178 }
179
180 func (rp *relyingParty) ErrorHandler() func(http.ResponseWriter, *http.Request, string, string, string) {
181 if rp.errorHandler == nil {
182 rp.errorHandler = DefaultErrorHandler
183 }
184 return rp.errorHandler
185 }
186
187 func (rp *relyingParty) UnauthorizedHandler() func(http.ResponseWriter, *http.Request, string, string) {
188 if rp.unauthorizedHandler == nil {
189 rp.unauthorizedHandler = DefaultUnauthorizedHandler
190 }
191 return rp.unauthorizedHandler
192 }
193
194 // Logger returns the logger configured with [WithLogger], or [slog.Default] if none was set.
195 // Deprecated: configure logging with [slog.SetDefault].
196 func (rp *relyingParty) Logger(context.Context) (*slog.Logger, bool) {
197 if rp.logger != nil {
198 return rp.logger, true
199 }
200 return slog.Default(), true
201 }
202
203 // NewRelyingPartyOAuth creates an (OAuth2) RelyingParty with the given
204 // OAuth2 Config and possible configOptions
205 // it will use the AuthURL and TokenURL set in config
206 func NewRelyingPartyOAuth(config *oauth2.Config, options ...Option) (RelyingParty, error) {
207 rp := &relyingParty{
208 oauthConfig: config,
209 httpClient: httphelper.DefaultHTTPClient,
210 oauth2Only: true,
211 unauthorizedHandler: DefaultUnauthorizedHandler,
212 oauthAuthStyle: oauth2.AuthStyleAutoDetect,
213 pkce: pkceDisabled,
214 }
215
216 for _, optFunc := range options {
217 if err := optFunc(rp); err != nil {
218 return nil, err
219 }
220 }
221
222 if rp.pkce == pkceFromDiscovery {
223 return nil, fmt.Errorf(
224 "%w: PKCE from discovery is not supported for OAuth2 only relying parties",
225 ErrInvalidOption,
226 )
227 }
228
229 rp.oauthConfig.Endpoint.AuthStyle = rp.oauthAuthStyle
230
231 // avoid races by calling these early
232 _ = rp.IDTokenVerifier() // sets idTokenVerifier
233 _ = rp.ErrorHandler() // sets errorHandler
234 _ = rp.UnauthorizedHandler() // sets unauthorizedHandler
235
236 return rp, nil
237 }
238
239 // NewRelyingPartyOIDC creates an (OIDC) RelyingParty with the given
240 // issuer, clientID, clientSecret, redirectURI, scopes and possible configOptions
241 // it will run discovery on the provided issuer and use the found endpoints
242 func NewRelyingPartyOIDC(ctx context.Context, issuer, clientID, clientSecret, redirectURI string, scopes []string, options ...Option) (RelyingParty, error) {
243 rp := &relyingParty{
244 issuer: issuer,
245 oauthConfig: &oauth2.Config{
246 ClientID: clientID,
247 ClientSecret: clientSecret,
248 RedirectURL: redirectURI,
249 Scopes: scopes,
250 },
251 httpClient: httphelper.DefaultHTTPClient,
252 oauth2Only: false,
253 oauthAuthStyle: oauth2.AuthStyleAutoDetect,
254 pkce: pkceDisabled,
255 }
256
257 for _, optFunc := range options {
258 if err := optFunc(rp); err != nil {
259 return nil, err
260 }
261 }
262 discoveryConfiguration, err := client.Discover(ctx, rp.issuer, rp.httpClient, rp.DiscoveryEndpoint)
263 if err != nil {
264 return nil, err
265 }
266 if rp.useSigningAlgsFromDiscovery {
267 rp.verifierOpts = append(rp.verifierOpts, WithSupportedSigningAlgorithms(discoveryConfiguration.IDTokenSigningAlgValuesSupported...))
268 }
269 endpoints := GetEndpoints(discoveryConfiguration)
270 rp.oauthConfig.Endpoint = endpoints.Endpoint
271 rp.endpoints = endpoints
272
273 rp.oauthConfig.Endpoint.AuthStyle = rp.oauthAuthStyle
274 rp.endpoints.Endpoint.AuthStyle = rp.oauthAuthStyle
275
276 if rp.pkce == pkceFromDiscovery {
277 if slices.ContainsFunc(
278 discoveryConfiguration.CodeChallengeMethodsSupported,
279 func(method oidc.CodeChallengeMethod) bool {
280 return method == oidc.CodeChallengeMethodPlain ||
281 method == oidc.CodeChallengeMethodS256
282 },
283 ) {
284 rp.pkce = pkceEnabled
285 } else {
286 rp.pkce = pkceDisabled
287 }
288 }
289
290 // avoid races by calling these early
291 _ = rp.IDTokenVerifier() // sets idTokenVerifier
292 _ = rp.ErrorHandler() // sets errorHandler
293 _ = rp.UnauthorizedHandler() // sets unauthorizedHandler
294
295 return rp, nil
296 }
297
298 // Option is the type for providing dynamic options to the relyingParty
299 type Option func(*relyingParty) error
300
301 func WithCustomDiscoveryUrl(url string) Option {
302 return func(rp *relyingParty) error {
303 rp.DiscoveryEndpoint = url
304 return nil
305 }
306 }
307
308 // WithCookieHandler set a `CookieHandler` for securing the various redirects
309 func WithCookieHandler(cookieHandler *httphelper.CookieHandler) Option {
310 return func(rp *relyingParty) error {
311 rp.cookieHandler = cookieHandler
312 return nil
313 }
314 }
315
316 // WithPKCE sets the RP to use PKCE (oauth2 code challenge)
317 // it also sets a `CookieHandler` for securing the various redirects
318 // and exchanging the code challenge
319 func WithPKCE(cookieHandler *httphelper.CookieHandler) Option {
320 return func(rp *relyingParty) error {
321 rp.pkce = pkceEnabled
322 rp.cookieHandler = cookieHandler
323 return nil
324 }
325 }
326
327 // WithPKCEFromDiscovery enables Oauth2 Code Challenge if support is found in the discovery response from the OP.
328 // Passing this option to an Oauth2-only RP will result in an error, as there is no discovery call.
329 // It also sets a `CookieHandler` for securing the various redirects
330 // and exchanging the code challenge
331 func WithPKCEFromDiscovery(cookieHandler *httphelper.CookieHandler) Option {
332 return func(rp *relyingParty) error {
333 rp.pkce = pkceFromDiscovery
334 rp.cookieHandler = cookieHandler
335 return nil
336 }
337 }
338
339 // WithHTTPClient provides the ability to set an http client to be used for the relaying party and verifier
340 func WithHTTPClient(client *http.Client) Option {
341 return func(rp *relyingParty) error {
342 rp.httpClient = client
343 return nil
344 }
345 }
346
347 func WithErrorHandler(errorHandler ErrorHandler) Option {
348 return func(rp *relyingParty) error {
349 rp.errorHandler = errorHandler
350 return nil
351 }
352 }
353
354 func WithUnauthorizedHandler(unauthorizedHandler UnauthorizedHandler) Option {
355 return func(rp *relyingParty) error {
356 rp.unauthorizedHandler = unauthorizedHandler
357 return nil
358 }
359 }
360
361 func WithAuthStyle(oauthAuthStyle oauth2.AuthStyle) Option {
362 return func(rp *relyingParty) error {
363 rp.oauthAuthStyle = oauthAuthStyle
364 return nil
365 }
366 }
367
368 func WithVerifierOpts(opts ...VerifierOption) Option {
369 return func(rp *relyingParty) error {
370 rp.verifierOpts = opts
371 return nil
372 }
373 }
374
375 // WithClientKey specifies the path to the key.json to be used for the JWT Profile Client Authentication on the token endpoint
376 //
377 // Deprecated: use WithJWTProfile(SignerFromKeyPath(path)), resp. WithJWTProfile(SignerFromKeyAndKeyID(key, keyID) instead.
378 func WithClientKey(path string) Option {
379 return WithJWTProfile(SignerFromKeyPath(path))
380 }
381
382 // WithJWTProfile creates a signer used for the JWT Profile Client Authentication on the token endpoint
383 // When creating the signer, be sure to include the KeyID in the SigningKey.
384 // See client.NewSignerFromPrivateKeyByte for an example.
385 func WithJWTProfile(signerFromKey SignerFromKey) Option {
386 return func(rp *relyingParty) error {
387 signer, err := signerFromKey()
388 if err != nil {
389 return err
390 }
391 rp.signer = signer
392 return nil
393 }
394 }
395
396 // WithLogger sets the logger returned by [RelyingParty.Logger].
397 // OIDC package logging uses the global [slog] default; prefer [slog.SetDefault].
398 // Deprecated: use [slog.SetDefault].
399 func WithLogger(logger *slog.Logger) Option {
400 return func(rp *relyingParty) error {
401 rp.logger = logger
402 return nil
403 }
404 }
405
406 // WithSigningAlgsFromDiscovery appends the [WithSupportedSigningAlgorithms] option to the Verifier Options.
407 // The algorithms returned in the `id_token_signing_alg_values_supported` from the discovery response will be set.
408 func WithSigningAlgsFromDiscovery() Option {
409 return func(rp *relyingParty) error {
410 rp.useSigningAlgsFromDiscovery = true
411 return nil
412 }
413 }
414
415 type SignerFromKey func() (jose.Signer, error)
416
417 // Deprecated: use [SignerFromKeyAndKeyID] instead.
418 // The function will be removed in the next major release.
419 func SignerFromKeyPath(path string) SignerFromKey {
420 return func() (jose.Signer, error) {
421 config, err := client.ConfigFromKeyFile(path)
422 if err != nil {
423 return nil, err
424 }
425 return client.NewSignerFromPrivateKeyByte([]byte(config.Key), config.KeyID)
426 }
427 }
428
429 // Deprecated: use [SignerFromKeyAndKeyID] instead.
430 // The function will be removed in the next major release.
431 func SignerFromKeyFile(fileData []byte) SignerFromKey {
432 return func() (jose.Signer, error) {
433 config, err := client.ConfigFromKeyFileData(fileData)
434 if err != nil {
435 return nil, err
436 }
437 return client.NewSignerFromPrivateKeyByte([]byte(config.Key), config.KeyID)
438 }
439 }
440
441 func SignerFromKeyAndKeyID(key []byte, keyID string) SignerFromKey {
442 return func() (jose.Signer, error) {
443 return client.NewSignerFromPrivateKeyByte(key, keyID)
444 }
445 }
446
447 // AuthURL returns the auth request url
448 // (wrapping the oauth2 `AuthCodeURL`)
449 func AuthURL(state string, rp RelyingParty, opts ...AuthURLOpt) string {
450 authOpts := make([]oauth2.AuthCodeOption, 0)
451 for _, opt := range opts {
452 authOpts = append(authOpts, opt()...)
453 }
454 if configured, ok := keyBindingRP(rp); ok {
455 authOpts = append(authOpts, oauth2.SetAuthURLParam(oidc.DPoPJKTParam, configured.KeyBindingThumbprint()))
456 }
457 return rp.OAuthConfig().AuthCodeURL(state, authOpts...)
458 }
459
460 // AuthURLHandler extends the `AuthURL` method with an http redirect handler
461 // including handling setting cookie for secure `state` transfer.
462 // Custom parameters can optionally be set to the redirect URL.
463 func AuthURLHandler(stateFn func() string, rp RelyingParty, urlParam ...URLParamOpt) http.HandlerFunc {
464 return func(w http.ResponseWriter, r *http.Request) {
465 opts := make([]AuthURLOpt, len(urlParam))
466 for i, p := range urlParam {
467 opts[i] = AuthURLOpt(p)
468 }
469
470 state := stateFn()
471 if err := trySetStateCookie(r, w, state, rp); err != nil {
472 unauthorizedError(w, r, "failed to create state cookie: "+err.Error(), state, rp)
473 return
474 }
475 if rp.IsPKCE() {
476 var codeChallenge string
477 var err error
478 if rp.CookieHandler().IsRequestAware() {
479 codeChallenge, err = GenerateAndStoreCodeChallengeWithRequest(r, w, rp)
480 } else {
481 codeChallenge, err = GenerateAndStoreCodeChallenge(w, rp)
482 }
483
484 if err != nil {
485 unauthorizedError(w, r, "failed to create code challenge: "+err.Error(), state, rp)
486 return
487 }
488 opts = append(opts, WithCodeChallenge(codeChallenge))
489 }
490
491 http.Redirect(w, r, AuthURL(state, rp, opts...), http.StatusFound)
492 }
493 }
494
495 // GenerateAndStoreCodeChallenge generates a PKCE code challenge and stores its verifier into a secure cookie
496 func GenerateAndStoreCodeChallenge(w http.ResponseWriter, rp RelyingParty) (string, error) {
497 codeVerifier := base64.RawURLEncoding.EncodeToString([]byte(uuid.New().String()))
498 if err := rp.CookieHandler().SetCookie(w, pkceCode, codeVerifier); err != nil {
499 return "", err
500 }
501 return oidc.NewSHACodeChallenge(codeVerifier), nil
502 }
503
504 // GenerateAndStoreCodeChallenge generates a PKCE code challenge and stores its verifier into a secure cookie
505 func GenerateAndStoreCodeChallengeWithRequest(r *http.Request, w http.ResponseWriter, rp RelyingParty) (string, error) {
506 codeVerifier := base64.RawURLEncoding.EncodeToString([]byte(uuid.New().String()))
507 if err := rp.CookieHandler().SetRequestAwareCookie(r, w, pkceCode, codeVerifier); err != nil {
508 return "", err
509 }
510 return oidc.NewSHACodeChallenge(codeVerifier), nil
511 }
512
513 // ErrMissingIDToken is returned when an id_token was expected,
514 // but not received in the token response.
515 var ErrMissingIDToken = errors.New("id_token missing")
516
517 func verifyTokenResponse[C oidc.IDClaims](ctx context.Context, token *oauth2.Token, rp RelyingParty) (*oidc.Tokens[C], error) {
518 ctx, span := client.Tracer.Start(ctx, "verifyTokenResponse")
519 defer span.End()
520
521 if rp.IsOAuth2Only() {
522 return &oidc.Tokens[C]{Token: token}, nil
523 }
524 idTokenString, ok := token.Extra(idTokenKey).(string)
525 if !ok {
526 return &oidc.Tokens[C]{Token: token}, ErrMissingIDToken
527 }
528 idToken, err := VerifyTokens[C](ctx, token.AccessToken, idTokenString, rp.IDTokenVerifier())
529 if err != nil {
530 return nil, err
531 }
532 if configured, ok := keyBindingRP(rp); ok {
533 if err := verifyKeyBindingIDToken(idTokenString, idToken.GetSignatureAlgorithm(), configured.KeyBindingThumbprint()); err != nil {
534 return nil, err
535 }
536 }
537 return &oidc.Tokens[C]{Token: token, IDTokenClaims: idToken, IDToken: idTokenString}, nil
538 }
539
540 // CodeExchange handles the oauth2 code exchange, extracting and validating the id_token
541 // returning it parsed together with the oauth2 tokens (access, refresh)
542 func CodeExchange[C oidc.IDClaims](ctx context.Context, code string, rp RelyingParty, opts ...CodeExchangeOpt) (tokens *oidc.Tokens[C], err error) {
543 ctx, codeExchangeSpan := client.Tracer.Start(ctx, "CodeExchange")
544 defer codeExchangeSpan.End()
545
546 httpClient := rp.HttpClient()
547 if configured, ok := keyBindingRP(rp); ok {
548 httpClient, err = keyBindingHTTPClient(httpClient, configured, code, rp.OAuthConfig().Endpoint.TokenURL)
549 if err != nil {
550 return nil, err
551 }
552 }
553 ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
554 codeOpts := make([]oauth2.AuthCodeOption, 0)
555 for _, opt := range opts {
556 codeOpts = append(codeOpts, opt()...)
557 }
558
559 ctx, oauthExchangeSpan := client.Tracer.Start(ctx, "OAuthExchange")
560 token, err := rp.OAuthConfig().Exchange(ctx, code, codeOpts...)
561 if err != nil {
562 return nil, err
563 }
564 oauthExchangeSpan.End()
565 return verifyTokenResponse[C](ctx, token, rp)
566 }
567
568 // ClientCredentials requests an access token using the `client_credentials` grant,
569 // as defined in [RFC 6749, section 4.4].
570 //
571 // As there is no user associated to the request an ID Token can never be returned.
572 // Client Credentials are undefined in OpenID Connect and is a pure OAuth2 grant.
573 // Furthermore, the server SHOULD NOT return a refresh token.
574 //
575 // [RFC 6749, section 4.4]: https://datatracker.ietf.org/doc/html/rfc6749#section-4.4
576 func ClientCredentials(ctx context.Context, rp RelyingParty, endpointParams url.Values) (token *oauth2.Token, err error) {
577 ctx, span := client.Tracer.Start(ctx, "ClientCredentials")
578 defer span.End()
579
580 ctx = context.WithValue(ctx, oauth2.HTTPClient, rp.HttpClient())
581 config := clientcredentials.Config{
582 ClientID: rp.OAuthConfig().ClientID,
583 ClientSecret: rp.OAuthConfig().ClientSecret,
584 TokenURL: rp.OAuthConfig().Endpoint.TokenURL,
585 Scopes: rp.OAuthConfig().Scopes,
586 EndpointParams: endpointParams,
587 AuthStyle: rp.OAuthConfig().Endpoint.AuthStyle,
588 }
589 return config.Token(ctx)
590 }
591
592 type CodeExchangeCallback[C oidc.IDClaims] func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[C], state string, rp RelyingParty)
593
594 // CodeExchangeHandler extends the `CodeExchange` method with an http handler
595 // including cookie handling for secure `state` transfer
596 // and optional PKCE code verifier checking.
597 // Custom parameters can optionally be set to the token URL.
598 func CodeExchangeHandler[C oidc.IDClaims](callback CodeExchangeCallback[C], rp RelyingParty, urlParam ...URLParamOpt) http.HandlerFunc {
599 return func(w http.ResponseWriter, r *http.Request) {
600 ctx, span := client.Tracer.Start(r.Context(), "CodeExchangeHandler")
601 r = r.WithContext(ctx)
602 defer span.End()
603
604 state, err := tryReadStateCookie(w, r, rp)
605 if err != nil {
606 unauthorizedError(w, r, "failed to get state: "+err.Error(), state, rp)
607 return
608 }
609 if errValue := r.FormValue("error"); errValue != "" {
610 rp.ErrorHandler()(w, r, errValue, r.FormValue("error_description"), state)
611 return
612 }
613 codeOpts := make([]CodeExchangeOpt, len(urlParam))
614 for i, p := range urlParam {
615 codeOpts[i] = CodeExchangeOpt(p)
616 }
617
618 if rp.IsPKCE() {
619 codeVerifier, err := rp.CookieHandler().CheckCookie(r, pkceCode)
620 if err != nil {
621 unauthorizedError(w, r, "failed to get code verifier: "+err.Error(), state, rp)
622 return
623 }
624 codeOpts = append(codeOpts, WithCodeVerifier(codeVerifier))
625 rp.CookieHandler().DeleteCookie(w, pkceCode)
626 }
627 if rp.Signer() != nil {
628 assertion, err := client.SignedJWTProfileAssertion(rp.OAuthConfig().ClientID, []string{rp.Issuer(), rp.OAuthConfig().Endpoint.TokenURL}, time.Hour, rp.Signer())
629 if err != nil {
630 unauthorizedError(w, r, "failed to build assertion: "+err.Error(), state, rp)
631 return
632 }
633 codeOpts = append(codeOpts, WithClientAssertionJWT(assertion))
634 }
635 tokens, err := CodeExchange[C](r.Context(), r.FormValue("code"), rp, codeOpts...)
636 if err != nil {
637 unauthorizedError(w, r, "failed to exchange token: "+err.Error(), state, rp)
638 return
639 }
640 callback(w, r, tokens, state, rp)
641 }
642 }
643
644 type SubjectGetter interface {
645 GetSubject() string
646 }
647
648 type CodeExchangeUserinfoCallback[C oidc.IDClaims, U SubjectGetter] func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[C], state string, provider RelyingParty, info U)
649
650 // UserinfoCallback wraps the callback function of the CodeExchangeHandler
651 // and calls the userinfo endpoint with the access token
652 // on success it will pass the userinfo into its callback function as well
653 func UserinfoCallback[C oidc.IDClaims, U SubjectGetter](f CodeExchangeUserinfoCallback[C, U]) CodeExchangeCallback[C] {
654 return func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[C], state string, rp RelyingParty) {
655 ctx, span := client.Tracer.Start(r.Context(), "UserinfoCallback")
656 r = r.WithContext(ctx)
657 defer span.End()
658
659 info, err := Userinfo[U](r.Context(), tokens.AccessToken, tokens.Type(), tokens.IDTokenClaims.GetSubject(), rp)
660 if err != nil {
661 unauthorizedError(w, r, "userinfo failed: "+err.Error(), state, rp)
662 return
663 }
664 f(w, r, tokens, state, rp, info)
665 }
666 }
667
668 // Userinfo will call the OIDC [UserInfo] Endpoint with the provided token and returns
669 // the response in an instance of type U.
670 // [*oidc.UserInfo] can be used as a good example, or use a custom type if type-safe
671 // access to custom claims is needed.
672 //
673 // [UserInfo]: https://openid.net/specs/openid-connect-core-1_0.html#UserInfo
674 func Userinfo[U SubjectGetter](ctx context.Context, token, tokenType, subject string, rp RelyingParty) (userinfo U, err error) {
675 var nilU U
676 ctx, span := client.Tracer.Start(ctx, "Userinfo")
677 defer span.End()
678
679 req, err := http.NewRequestWithContext(ctx, http.MethodGet, rp.UserinfoEndpoint(), nil)
680 if err != nil {
681 return nilU, err
682 }
683 req.Header.Set("authorization", tokenType+" "+token)
684 if err := httphelper.HttpRequest(rp.HttpClient(), req, &userinfo); err != nil {
685 return nilU, err
686 }
687 if userinfo.GetSubject() != subject {
688 return nilU, ErrUserInfoSubNotMatching
689 }
690 return userinfo, nil
691 }
692
693 func trySetStateCookie(r *http.Request, w http.ResponseWriter, state string, rp RelyingParty) error {
694 if rp.CookieHandler() != nil {
695 var err error
696 if rp.CookieHandler().IsRequestAware() {
697 err = rp.CookieHandler().SetRequestAwareCookie(r, w, stateParam, state)
698 } else {
699 err = rp.CookieHandler().SetCookie(w, stateParam, state)
700 }
701
702 if err != nil {
703 return err
704 }
705 }
706 return nil
707 }
708
709 func tryReadStateCookie(w http.ResponseWriter, r *http.Request, rp RelyingParty) (state string, err error) {
710 if rp.CookieHandler() == nil {
711 return r.FormValue(stateParam), nil
712 }
713 state, err = rp.CookieHandler().CheckQueryCookie(r, stateParam)
714 if err != nil {
715 return "", err
716 }
717 rp.CookieHandler().DeleteCookie(w, stateParam)
718 return state, nil
719 }
720
721 type OptionFunc func(RelyingParty)
722
723 type Endpoints struct {
724 oauth2.Endpoint
725 IntrospectURL string
726 UserinfoURL string
727 JKWsURL string
728 EndSessionURL string
729 RevokeURL string
730 DeviceAuthorizationURL string
731 }
732
733 func GetEndpoints(discoveryConfig *oidc.DiscoveryConfiguration) Endpoints {
734 return Endpoints{
735 Endpoint: oauth2.Endpoint{
736 AuthURL: discoveryConfig.AuthorizationEndpoint,
737 TokenURL: discoveryConfig.TokenEndpoint,
738 },
739 IntrospectURL: discoveryConfig.IntrospectionEndpoint,
740 UserinfoURL: discoveryConfig.UserinfoEndpoint,
741 JKWsURL: discoveryConfig.JwksURI,
742 EndSessionURL: discoveryConfig.EndSessionEndpoint,
743 RevokeURL: discoveryConfig.RevocationEndpoint,
744 DeviceAuthorizationURL: discoveryConfig.DeviceAuthorizationEndpoint,
745 }
746 }
747
748 // withURLParam sets custom url parameters.
749 // This is the generalized, unexported, function used by both
750 // URLParamOpt and AuthURLOpt.
751 func withURLParam(key, value string) func() []oauth2.AuthCodeOption {
752 return func() []oauth2.AuthCodeOption {
753 return []oauth2.AuthCodeOption{
754 oauth2.SetAuthURLParam(key, value),
755 }
756 }
757 }
758
759 // withPrompt sets the `prompt` params in the auth request
760 // This is the generalized, unexported, function used by both
761 // URLParamOpt and AuthURLOpt.
762 func withPrompt(prompt ...string) func() []oauth2.AuthCodeOption {
763 return withURLParam("prompt", oidc.SpaceDelimitedArray(prompt).String())
764 }
765
766 type URLParamOpt func() []oauth2.AuthCodeOption
767
768 // WithURLParam allows setting custom key-vale pairs
769 // to an OAuth2 URL.
770 func WithURLParam(key, value string) URLParamOpt {
771 return withURLParam(key, value)
772 }
773
774 // WithPromptURLParam sets the `prompt` parameter in a URL.
775 func WithPromptURLParam(prompt ...string) URLParamOpt {
776 return withPrompt(prompt...)
777 }
778
779 // WithResponseModeURLParam sets the `response_mode` parameter in a URL.
780 func WithResponseModeURLParam(mode oidc.ResponseMode) URLParamOpt {
781 return withURLParam("response_mode", string(mode))
782 }
783
784 type AuthURLOpt func() []oauth2.AuthCodeOption
785
786 // WithCodeChallenge sets the `code_challenge` params in the auth request
787 func WithCodeChallenge(codeChallenge string) AuthURLOpt {
788 return func() []oauth2.AuthCodeOption {
789 return []oauth2.AuthCodeOption{
790 oauth2.SetAuthURLParam("code_challenge", codeChallenge),
791 oauth2.SetAuthURLParam("code_challenge_method", "S256"),
792 }
793 }
794 }
795
796 // WithPrompt sets the `prompt` params in the auth request
797 func WithPrompt(prompt ...string) AuthURLOpt {
798 return withPrompt(prompt...)
799 }
800
801 type CodeExchangeOpt func() []oauth2.AuthCodeOption
802
803 // WithCodeVerifier sets the `code_verifier` param in the token request
804 func WithCodeVerifier(codeVerifier string) CodeExchangeOpt {
805 return func() []oauth2.AuthCodeOption {
806 return []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("code_verifier", codeVerifier)}
807 }
808 }
809
810 // WithClientAssertionJWT sets the `client_assertion` param in the token request
811 func WithClientAssertionJWT(clientAssertion string) CodeExchangeOpt {
812 return func() []oauth2.AuthCodeOption {
813 return client.ClientAssertionCodeOptions(clientAssertion)
814 }
815 }
816
817 type tokenEndpointCaller struct {
818 RelyingParty
819 httpClient *http.Client
820 }
821
822 func (t tokenEndpointCaller) TokenEndpoint() string {
823 return t.OAuthConfig().Endpoint.TokenURL
824 }
825
826 func (t tokenEndpointCaller) HttpClient() *http.Client {
827 if t.httpClient != nil {
828 return t.httpClient
829 }
830 return t.RelyingParty.HttpClient()
831 }
832
833 type RefreshTokenRequest struct {
834 RefreshToken string `schema:"refresh_token"`
835 Scopes oidc.SpaceDelimitedArray `schema:"scope,omitempty"`
836 ClientID string `schema:"client_id,omitempty"`
837 ClientSecret string `schema:"client_secret,omitempty"`
838 ClientAssertion string `schema:"client_assertion,omitempty"`
839 ClientAssertionType string `schema:"client_assertion_type,omitempty"`
840 GrantType oidc.GrantType `schema:"grant_type"`
841 }
842
843 // Deprecated: This function is no longer invoked because it violates
844 // RFC 6749 ยง2.3: The client MUST NOT use more than one authentication method in each request.
845 //
846 // Configure the OAuth2 endpoint AuthStyle (e.g., oauth2.AuthStyleInHeader)
847 // or use the "authFn" parameter in the related functions for custom needs.
848 func (r RefreshTokenRequest) Auth(req *http.Request) {
849 if r.ClientSecret != "" {
850 req.SetBasicAuth(url.QueryEscape(r.ClientID), url.QueryEscape(r.ClientSecret))
851 }
852 }
853
854 // RefreshTokens performs a token refresh. If it doesn't error, it will always
855 // provide a new AccessToken. It may provide a new RefreshToken, and if it does, then
856 // the old one should be considered invalid.
857 //
858 // In case the RP is not OAuth2 only and an IDToken was part of the response,
859 // the IDToken and AccessToken will be verified
860 // and the IDToken and IDTokenClaims fields will be populated in the returned object.
861 func RefreshTokens[C oidc.IDClaims](ctx context.Context, rp RelyingParty, refreshToken, clientAssertion, clientAssertionType string) (*oidc.Tokens[C], error) {
862 ctx, span := client.Tracer.Start(ctx, "RefreshTokens")
863 defer span.End()
864
865 var authFn httphelper.RequestAuthorization
866 request := RefreshTokenRequest{
867 RefreshToken: refreshToken,
868 Scopes: rp.OAuthConfig().Scopes,
869 GrantType: oidc.GrantTypeRefreshToken,
870 }
871
872 // https://datatracker.ietf.org/doc/html/rfc6749#section-2.3
873 // The client MUST NOT use more than one authentication method in each request.
874 switch rp.OAuthConfig().Endpoint.AuthStyle {
875 case oauth2.AuthStyleInHeader:
876 if clientAssertion != "" {
877 return nil, errors.New("client assertion is not supported with AuthStyleInHeader")
878 }
879 authFn = httphelper.AuthorizeBasic(rp.OAuthConfig().ClientID, rp.OAuthConfig().ClientSecret)
880 default:
881 // use client id and secret in the request body
882 if clientAssertion != "" && clientAssertionType != "" {
883 request.ClientAssertion = clientAssertion
884 request.ClientAssertionType = clientAssertionType
885 } else {
886 request.ClientID = rp.OAuthConfig().ClientID
887 request.ClientSecret = rp.OAuthConfig().ClientSecret
888 }
889 }
890
891 httpClient := rp.HttpClient()
892 if configured, ok := keyBindingRP(rp); ok {
893 var err error
894 httpClient, err = keyBindingHTTPClient(httpClient, configured, "", rp.OAuthConfig().Endpoint.TokenURL)
895 if err != nil {
896 return nil, err
897 }
898 }
899 caller := tokenEndpointCaller{RelyingParty: rp, httpClient: httpClient}
900 newToken, err := client.CallTokenEndpointWithAuthFn(ctx, request, authFn, caller)
901 if err != nil {
902 return nil, err
903 }
904 tokens, err := verifyTokenResponse[C](ctx, newToken, rp)
905 if err == nil || errors.Is(err, ErrMissingIDToken) {
906 // https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse
907 // ...except that it might not contain an id_token.
908 return tokens, nil
909 }
910 return nil, err
911 }
912
913 func EndSession(ctx context.Context, rp RelyingParty, idToken, optionalRedirectURI, optionalState, optionalLogoutHint string, optionalLocales oidc.Locales) (*url.URL, error) {
914 ctx, span := client.Tracer.Start(ctx, "EndSession")
915 defer span.End()
916
917 request := oidc.EndSessionRequest{
918 IdTokenHint: idToken,
919 ClientID: rp.OAuthConfig().ClientID,
920 PostLogoutRedirectURI: optionalRedirectURI,
921 State: optionalState,
922 LogoutHint: optionalLogoutHint,
923 UILocales: optionalLocales,
924 }
925 return client.CallEndSessionEndpoint(ctx, request, nil, rp)
926 }
927
928 // RevokeToken requires a RelyingParty that is also a client.RevokeCaller. The RelyingParty
929 // returned by NewRelyingPartyOIDC() meets that criteria, but the one returned by
930 // NewRelyingPartyOAuth() does not.
931 //
932 // tokenTypeHint should be either "id_token" or "refresh_token".
933 func RevokeToken(ctx context.Context, rp RelyingParty, token string, tokenTypeHint string) error {
934 ctx, span := client.Tracer.Start(ctx, "RevokeToken")
935 defer span.End()
936
937 request := client.RevokeRequest{
938 Token: token,
939 TokenTypeHint: tokenTypeHint,
940 }
941 var authFn httphelper.RequestAuthorization
942
943 // https://datatracker.ietf.org/doc/html/rfc6749#section-2.3
944 // The client MUST NOT use more than one authentication method in each request.
945 switch rp.OAuthConfig().Endpoint.AuthStyle {
946 case oauth2.AuthStyleInHeader:
947 authFn = httphelper.AuthorizeBasic(rp.OAuthConfig().ClientID, rp.OAuthConfig().ClientSecret)
948 default:
949 // use client id and secret in the request body
950 request.ClientID = rp.OAuthConfig().ClientID
951 request.ClientSecret = rp.OAuthConfig().ClientSecret
952 }
953
954 if rc, ok := rp.(client.RevokeCaller); ok && rc.GetRevokeEndpoint() != "" {
955 return client.CallRevokeEndpoint(ctx, request, authFn, rc)
956 }
957 return ErrRelyingPartyNotSupportRevokeCaller
958 }
959
960 func unauthorizedError(w http.ResponseWriter, r *http.Request, desc string, state string, rp RelyingParty) {
961 if rp, ok := rp.(HasUnauthorizedHandler); ok {
962 rp.UnauthorizedHandler()(w, r, desc, state)
963 return
964 }
965 http.Error(w, desc, http.StatusUnauthorized)
966 }