Debian Codegraph @

internal/oauth2/providers/generic/oidc.go

raw
1 package generic
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7
8 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config"
9 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2"
10 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/idtoken"
11 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/types"
12 "github.com/zitadel/oidc/v3/pkg/client/rp"
13 "github.com/zitadel/oidc/v3/pkg/oidc"
14 )
15
16 // GetRefreshToken returns the provider refresh token from the OAuth2 token response.
17 func (p Provider) GetRefreshToken(tokens *idtoken.IDToken) (string, error) {
18 if tokens == nil {
19 return "", oauth2.ErrMissingToken
20 }
21
22 if tokens.RefreshToken == "" {
23 return "", oauth2.ErrNoRefreshToken
24 }
25
26 return tokens.RefreshToken, nil
27 }
28
29 // Refresh initiates a non-interactive authentication against the sso provider.
30 func (p Provider) Refresh(ctx context.Context, relyingParty rp.RelyingParty, refreshToken string) (*idtoken.IDToken, error) {
31 // Apply refresh nonce control based on configuration
32 if p.Conf.OAuth2.RefreshNonce == config.OAuth2RefreshNonceEmpty {
33 ctx = context.WithValue(ctx, types.CtxNonce{}, "")
34 }
35
36 tokens, err := rp.RefreshTokens[*idtoken.Claims](ctx, relyingParty, refreshToken, "", "")
37
38 // Only retry for auto mode when we get a nonce error
39 if p.Conf.OAuth2.RefreshNonce == config.OAuth2RefreshNonceAuto && errors.Is(err, oidc.ErrNonceInvalid) {
40 // OIDC spec says that nonce is optional for refresh tokens
41 // https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens
42 // This means that we have to retry the refresh without a nonce if we get an error,
43 // However, trying to refresh session with the same refresh token could lead into an error
44 // because refresh token may have a one time use policy
45 // see: https://github.com/zitadel/oidc/issues/509
46 ctx = context.WithValue(ctx, types.CtxNonce{}, "")
47 tokens, err = rp.RefreshTokens[*idtoken.Claims](ctx, relyingParty, refreshToken, "", "")
48 }
49
50 if err != nil {
51 return nil, fmt.Errorf("error from token exchange via refresh token: %w", err)
52 }
53
54 return tokens, nil
55 }
56
57 // RevokeRefreshToken revokes a refresh token when the relying party supports token revocation.
58 func (p Provider) RevokeRefreshToken(ctx context.Context, relyingParty rp.RelyingParty, refreshToken string) error {
59 err := rp.RevokeToken(ctx, relyingParty, refreshToken, "refresh_token")
60 if err != nil && !errors.Is(err, rp.ErrRelyingPartyNotSupportRevokeCaller) {
61 return fmt.Errorf("error revoke refresh token: %w", err)
62 }
63
64 return nil
65 }