oidc

package
v0.11.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 2, 2026 License: Apache-2.0 Imports: 30 Imported by: 3

Documentation

Overview

Package oidc provides an OpenID Connect (OIDC) client and utilities for token validation and management.

Index

Constants

View Source
const (
	ProviderTypeGitHub        = "github"
	ProviderTypeGitHubActions = "githubactions"
	ProviderTypeKeycloak      = "keycloak"
	ProviderTypeFlyIO         = "flyio"
	ProviderTypeAWS           = "aws"
)

Recognised EndpointConfig.Type values.

Variables

View Source
var (
	ErrInvalidToken    = errors.New("invalid token")
	ErrTokenValidation = errors.New("token validation failed")
	ErrInvalidClaims   = errors.New("invalid claims format")
)

Sentinel errors returned by token handling and validation in this package.

View Source
var (
	ErrNoIdentity = errors.New("no identity information found in config")
)

ErrNoIdentity is returned when ClientConfig has neither a recognised platform type, a token file, nor client credentials to build a token source from.

Functions

func ClaimsFromContext added in v0.4.0

func ClaimsFromContext(ctx context.Context) any

ClaimsFromContext extracts OIDC claims from the request context. This is kept for backward compatibility and error reporting. For principal extraction, use auth.NewDefaultPrincipalExtractor or auth.NewDefaultPrincipalExtractorWithConfig instead.

func DefaultTokenSourceFactories

func DefaultTokenSourceFactories() map[string]TokenSourceFactory

DefaultTokenSourceFactories returns a copy of the default token source registry.

func DeviceCodeUIConsoleQR

func DeviceCodeUIConsoleQR(deviceCode *oauth2.DeviceAuthResponse) error

DeviceCodeUIConsoleQR renders deviceCode's verification URI as a QR code in the terminal.

func DeviceCodeUIConsoleText

func DeviceCodeUIConsoleText(deviceCode *oauth2.DeviceAuthResponse) error

DeviceCodeUIConsoleText prints deviceCode's verification URI (and code, if the URI doesn't already embed it) to stdout.

func ExtractClaims

func ExtractClaims[T jwtvalidator.CustomClaims](claims any) (jwtvalidator.RegisteredClaims, T, error)

ExtractClaims type-asserts claims to *jwtvalidator.ValidatedClaims and splits out its registered and typed custom claims (of type T). It returns an error if claims isn't a *jwtvalidator.ValidatedClaims, or if its CustomClaims is set but isn't of type T.

func NewHTTPClientFromConfig

func NewHTTPClientFromConfig(cfg *ClientConfig) (*http.Client, error)

NewHTTPClientFromConfig creates an HTTP client with a token source from a ClientConfig.

func NewMultiValidatorFromConfig

func NewMultiValidatorFromConfig(configs []ValidatorConfig, _ ...validator.Option) (jwt.TokenValidator, error)

NewMultiValidatorFromConfig creates a MultiValidator from multiple configs.

func NewTokenSourceFromConfig

func NewTokenSourceFromConfig(cfg ClientConfig) (oauth2.TokenSource, error)

NewTokenSourceFromConfig creates a token source from a ClientConfig.

func NewTokenSourceFromConfigWithFactories

func NewTokenSourceFromConfigWithFactories(cfg ClientConfig, factories map[string]TokenSourceFactory, store TokenStore, clock Clock, ctx context.Context) (oauth2.TokenSource, error)

NewTokenSourceFromConfigWithFactories creates a token source using a custom registry and dependencies.

func NewValidatorDebugger

func NewValidatorDebugger(v jwt.TokenValidator) jwt.TokenValidator

NewValidatorDebugger wraps a TokenValidator with debugging output, logged via the logger embedded in each call's ctx - see validatorDebugger.

func NewValidatorFromConfig

func NewValidatorFromConfig(cfg *ValidatorConfig) (jwt.TokenValidator, error)

NewValidatorFromConfig creates a TokenValidator from a ValidatorConfig.

func NewValidatorFromConfigWithOptions

func NewValidatorFromConfigWithOptions(cfg *ValidatorConfig, opts ...ValidatorOpt) (jwt.TokenValidator, error)

NewValidatorFromConfigWithOptions creates a TokenValidator from a ValidatorConfig using custom options.

func NewWaitingTokenSource

func NewWaitingTokenSource(ctx context.Context, source oauth2.TokenSource, interval, timeout time.Duration) oauth2.TokenSource

NewWaitingTokenSource returns a token source that waits for a token to be available, polling source every interval until it succeeds. A timeout of zero or less means wait indefinitely, until ctx is done - useful for a long-lived daemon coordinating with an out-of-band process (e.g. a bootstrap wizard) that may take an unbounded amount of time to produce a token, as opposed to a bounded timeout suited to a short-lived caller.

func NewWaitingTokenSourceFromConfig

func NewWaitingTokenSourceFromConfig(ctx context.Context, cfg ClientConfig, interval, timeout time.Duration) (oauth2.TokenSource, error)

NewWaitingTokenSourceFromConfig creates a waiting token source from a ClientConfig.

func ResolveTokenFromFile

func ResolveTokenFromFile(filePath string) (*oauth2.Token, error)

ResolveTokenFromFile loads an OAuth2 token from a file.

func SaveTokenToFile

func SaveTokenToFile(token *oauth2.Token, filePath string) error

SaveTokenToFile saves the provided OAuth2 token to a file.

func WithCustomClaims

func WithCustomClaims[T jwtvalidator.CustomClaims](t T) func(e Endpoint)

WithCustomClaims configures the endpoint to return a specific CustomClaims implementation during validation.

Types

type AWSCustomClaims added in v0.4.0

type AWSCustomClaims = aws.CustomClaims

AWSCustomClaims is an alias for aws.CustomClaims.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents an OIDC client.

func NewClient

func NewClient(endpoint Endpoint, opts ...ClientOpt) *Client

NewClient creates a new OIDC client with the provided endpoint and options.

func NewClientFromConfig

func NewClientFromConfig(config *ClientConfig, opts ...ClientOpt) (*Client, error)

NewClientFromConfig creates a new OIDC client from the provided configuration. Additional opts are applied after the config-derived client ID and secret, so callers can extend or override behavior (for example WithDeviceCodeUI) without re-deriving the endpoint/credential setup NewClientFromConfig already does.

func (*Client) AuthorizationCodeRedirectFlow

func (c *Client) AuthorizationCodeRedirectFlow(ctx context.Context, state string, scopes []string, redirectURI string, opts ...RequestOpt) (string, error)

AuthorizationCodeRedirectFlow generates the authorization URL for the Authorization Code Flow.

func (*Client) AuthorizationCodeToken

func (c *Client) AuthorizationCodeToken(ctx context.Context, code string, redirectURI string, opts ...RequestOpt) (*oauth2.Token, error)

AuthorizationCodeToken exchanges an authorization code for a token via the authorization_code grant.

func (*Client) ClientCredentialsToken

func (c *Client) ClientCredentialsToken(ctx context.Context, opts ...RequestOpt) (*oauth2.Token, error)

ClientCredentialsToken gets a token using the client_credentials grant. It sends the client_id and client_secret to the token endpoint and gets a token in response.

func (*Client) ClientID added in v0.9.1

func (c *Client) ClientID() string

ClientID returns the OAuth2 client ID this Client authenticates as. Used as the expected audience when validating ID tokens issued to this client.

func (*Client) DeviceToken

func (c *Client) DeviceToken(ctx context.Context, scopes ...string) (*oauth2.Token, error)

DeviceToken runs the OAuth2 Device Authorization Grant flow: it requests a device code, displays it to the user via c.deviceUI (or a console default), and polls until the token is issued.

func (*Client) Endpoint

func (c *Client) Endpoint() Endpoint

Endpoint returns the OIDC provider endpoint this Client was constructed with.

func (*Client) GothProvider

func (c *Client) GothProvider(callbackURL *url.URL, scopes ...string) (goth.Provider, error)

GothProvider returns a goth.Provider for this Client's endpoint, or an error if the endpoint doesn't support goth-based login flows.

func (*Client) HTTPClient

func (c *Client) HTTPClient(ctx context.Context, t *oauth2.Token) (*http.Client, error)

HTTPClient returns an *http.Client that attaches t as a bearer token, refreshing it via the OAuth2 flow when it expires.

func (*Client) IntrospectToken

func (c *Client) IntrospectToken(ctx context.Context, token string) (*IntrospectionResponse, error)

IntrospectToken introspects the token. It sends the token to the introspection endpoint and gets the response.

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context, refreshToken string, opts ...RequestOpt) (*oauth2.Token, error)

RefreshToken exchanges refreshToken for a new access token via the refresh_token grant.

func (*Client) RefreshingClientCredentialsToken

func (c *Client) RefreshingClientCredentialsToken(ctx context.Context, opts ...RequestOpt) (oauth2.TokenSource, error)

RefreshingClientCredentialsToken returns an oauth2.TokenSource that lazily fetches and refreshes a client_credentials token using c.

func (*Client) TokenSource

func (c *Client) TokenSource(t *oauth2.Token) (oauth2.TokenSource, error)

TokenSource returns an oauth2.TokenSource seeded with t that transparently refreshes the token via the OAuth2 flow when it expires.

func (*Client) ValidateToken

func (c *Client) ValidateToken(ctx context.Context, token string, audiences []string) (*jwtvalidator.ValidatedClaims, error)

ValidateToken VerifyToke verifies the token and returns the claims It fetches the verification keys from the OIDC server and uses them to verify the token.

type ClientConfig

type ClientConfig struct {
	// Provider     EndpointConfig    `json:"provider"` // e.g. "github", "keycloak"
	EndpointConfig `mapstructure:",squash"`

	ClientID     string            `json:"client_id"     mapstructure:"client-id"`
	ClientSecret util.MaskedString `json:"client_secret" mapstructure:"client-secret,omitempty"`

	Audience string `json:"audience,omitempty" mapstructure:"audience,omitempty"`

	// do these belong somewhere else?
	TokenFile string `json:"token_file,omitempty" mapstructure:"token-file,omitempty"`

	TLSClient tls.ClientConfig `json:"tls_client" mapstructure:"tls-client,omitempty"`
}

ClientConfig captures client credentials and token acquisition options for an OIDC provider.

type ClientOpt

type ClientOpt func(c *Client)

ClientOpt configures an OIDC Client.

func WithClientID

func WithClientID(clientID string) ClientOpt

WithClientID sets the client identifier used for OIDC flows.

func WithClientIDAndSecret

func WithClientIDAndSecret(clientID, clientSecret string) ClientOpt

WithClientIDAndSecret sets both the client ID and secret for the client.

func WithClock

func WithClock(clock Clock) ClientOpt

WithClock sets a custom clock for time-dependent behavior.

func WithDeviceCodeUI

func WithDeviceCodeUI(ui DeviceCodeUI) ClientOpt

WithDeviceCodeUI injects a custom device code UI handler for interactive flows.

func WithHTTPClient

func WithHTTPClient(doer HTTPDoer) ClientOpt

WithHTTPClient sets a custom HTTP client for outbound requests.

func WithJWKSProvider

func WithJWKSProvider(provider *jwks.CachingProvider) ClientOpt

WithJWKSProvider sets a custom JWKS caching provider for token validation.

func WithKeyCacheTTL

func WithKeyCacheTTL(ttl time.Duration) ClientOpt

WithKeyCacheTTL overrides the cache TTL for JWKS keys used during validation.

func WithKeyFunc

func WithKeyFunc(keyFunc func(context.Context) (any, error)) ClientOpt

WithKeyFunc sets a custom key function for token validation.

func WithValidatingSignatureAlgorithm

func WithValidatingSignatureAlgorithm(algorithm jwtvalidator.SignatureAlgorithm) ClientOpt

WithValidatingSignatureAlgorithm sets the signature algorithm used when validating ID tokens.

func WithValidatingSignatureAlgorithms added in v0.5.5

func WithValidatingSignatureAlgorithms(algorithms []jwtvalidator.SignatureAlgorithm) ClientOpt

WithValidatingSignatureAlgorithms sets the signature algorithms used when validating ID tokens. This option takes precedence over WithValidatingSignatureAlgorithm when both are set.

type Clock

type Clock interface {
	Now() time.Time
}

Clock abstracts time for deterministic tests.

type Config

type Config struct {
	ProviderMap ProviderMap `json:"providers" mapstructure:"providers"`
}

Config contains a collection of provider configurations.

type DeviceCodeUI

type DeviceCodeUI func(deviceCode *oauth2.DeviceAuthResponse) error

DeviceCodeUI presents a device authorization code to the user during the OAuth2 Device Authorization Grant flow.

type Endpoint

type Endpoint interface {
	URL() *url.URL
	DiscoveryEndpoint() (*url.URL, error)
	DiscoveredConfiguration(ctx context.Context) (*OpenIDConfiguration, error)
	OAuth2Endpoint(ctx context.Context) (oauth2.Endpoint, error)
}

Endpoint defines the interface for an OpenID Connect provider endpoint.

func NewEndpoint

func NewEndpoint(baseURL string, opts ...EndpointOption) (Endpoint, error)

NewEndpoint creates a generic OIDC Endpoint for baseURL, using standard OIDC discovery (.well-known/openid-configuration).

func NewEndpointFromConfig

func NewEndpointFromConfig(config *EndpointConfig) (Endpoint, error)

NewEndpointFromConfig creates the Endpoint implementation matching config.Type (github, githubactions, keycloak, flyio, aws), or a generic Endpoint if Type is unset but URL is provided.

func NewGitHubActionsEndpoint

func NewGitHubActionsEndpoint(baseURL string) (Endpoint, error)

NewGitHubActionsEndpoint creates a new GitHub Actions OIDC endpoint.

func NewGitHubEndpoint

func NewGitHubEndpoint(baseURL string) (Endpoint, error)

NewGitHubEndpoint creates a GitHubEndpoint for baseURL, defaulting to https://github.com if empty.

func NewKeycloakRealmEndpoint

func NewKeycloakRealmEndpoint(baseURLStr, realm string, opts ...EndpointOption) (Endpoint, error)

NewKeycloakRealmEndpoint creates the Endpoint for realm on the Keycloak server at baseURLStr in one call.

type EndpointConfig

type EndpointConfig struct {
	Type          string `json:"type,omitempty"           mapstructure:"type,omitempty"`
	URL           string `json:"url"                      mapstructure:"url"`
	KeycloakRealm string `json:"keycloak_realm,omitempty" mapstructure:"keycloak-realm,omitempty"`
}

EndpointConfig describes the issuer endpoint and any provider-specific options.

type EndpointOption

type EndpointOption func(e Endpoint)

EndpointOption is a functional option for configuring an Endpoint.

func WithHTTPDoer

func WithHTTPDoer(doer HTTPDoer) EndpointOption

WithHTTPDoer configures a custom HTTP client for endpoint discovery.

type FileTokenStore

type FileTokenStore struct {
	// contains filtered or unexported fields
}

FileTokenStore persists tokens in a file on disk.

func NewFileTokenStore

func NewFileTokenStore(path string) *FileTokenStore

NewFileTokenStore creates a file-based token store.

func (*FileTokenStore) LoadToken

func (s *FileTokenStore) LoadToken(_ context.Context) (*oauth2.Token, error)

LoadToken reads a token from disk.

func (*FileTokenStore) SaveToken

func (s *FileTokenStore) SaveToken(_ context.Context, token *oauth2.Token) error

SaveToken writes a token to disk.

type FlyIOCustomClaims added in v0.4.0

type FlyIOCustomClaims = flyio.CustomClaims

FlyIOCustomClaims is an alias for flyio.CustomClaims.

type GitHubActionsCustomClaims added in v0.4.0

type GitHubActionsCustomClaims = githubactions.CustomClaims

GitHubActionsCustomClaims is an alias for githubactions.CustomClaims.

type GitHubActionsEndpoint

type GitHubActionsEndpoint struct {
	// contains filtered or unexported fields
}

GitHubActionsEndpoint represents the GitHub Actions OIDC endpoint.

func (*GitHubActionsEndpoint) DiscoveredConfiguration

func (e *GitHubActionsEndpoint) DiscoveredConfiguration(ctx context.Context) (*OpenIDConfiguration, error)

DiscoveredConfiguration returns the OIDC configuration by fetching the discovery endpoint.

func (*GitHubActionsEndpoint) DiscoveryEndpoint

func (e *GitHubActionsEndpoint) DiscoveryEndpoint() (*url.URL, error)

DiscoveryEndpoint returns the OIDC discovery endpoint URL.

func (*GitHubActionsEndpoint) OAuth2Endpoint

func (e *GitHubActionsEndpoint) OAuth2Endpoint(ctx context.Context) (oauth2.Endpoint, error)

OAuth2Endpoint returns the OAuth2 endpoint configuration.

func (*GitHubActionsEndpoint) URL

func (e *GitHubActionsEndpoint) URL() *url.URL

URL returns the base URL for the GitHub Actions OIDC endpoint.

type GitHubEndpoint

type GitHubEndpoint struct {
	// contains filtered or unexported fields
}

GitHubEndpoint represents the GitHub OAuth endpoint.

func (*GitHubEndpoint) DiscoveredConfiguration

func (e *GitHubEndpoint) DiscoveredConfiguration(_ context.Context) (*OpenIDConfiguration, error)

DiscoveredConfiguration returns GitHub's OAuth endpoints, hardcoded since GitHub does not support OIDC discovery.

func (*GitHubEndpoint) DiscoveryEndpoint

func (e *GitHubEndpoint) DiscoveryEndpoint() (*url.URL, error)

DiscoveryEndpoint always returns an error: GitHub does not support OpenID Connect discovery.

func (*GitHubEndpoint) GothProvider

func (e *GitHubEndpoint) GothProvider(clientID, clientSecret string, callbackURL *url.URL, scopes ...string) (goth.Provider, error)

GothProvider returns a goth GitHub provider for this endpoint.

func (*GitHubEndpoint) OAuth2Endpoint

func (e *GitHubEndpoint) OAuth2Endpoint(_ context.Context) (oauth2.Endpoint, error)

OAuth2Endpoint returns golang.org/x/oauth2/endpoints.GitHub.

func (*GitHubEndpoint) URL

func (e *GitHubEndpoint) URL() *url.URL

URL returns the base URL of the GitHub OAuth endpoint.

type GothEndpoint

type GothEndpoint interface {
	GothProvider(clientID, clientSecret string, callbackURL *url.URL, scopes ...string) (goth.Provider, error)
}

GothEndpoint defines the interface for endpoints that support Goth provider creation.

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer abstracts HTTP calls for testability.

type IntrospectionResponse

type IntrospectionResponse struct {
	FlyIOCustomClaims
	GitHubActionsCustomClaims
	AWSCustomClaims

	ExpiresAt                           int      `json:"exp"`
	IssuedAt                            int      `json:"iat"`
	AuthTime                            int      `json:"auth_time"`
	ID                                  string   `json:"jti"`
	Issuer                              string   `json:"iss"`
	Audience                            string   `json:"aud"`
	Subject                             string   `json:"sub"`
	Type                                string   `json:"typ"`
	AuthorizedParty                     string   `json:"azp"`
	SessionID                           string   `json:"sid"`
	AuthenticationContextClassReference string   `json:"acr"`
	AllowedOrigins                      []string `json:"allowed-origins"` //nolint:tagliatelle // Keycloak's actual claim key, not ours to rename
	RealmAccess                         struct {
		Roles []string `json:"roles"`
	} `json:"realm_access"`
	ResourceAccess struct {
		Account struct {
			Roles []string `json:"roles"`
		} `json:"account"`
	} `json:"resource_access"`
	Scope             string   `json:"scope"`
	UserPrincipalName string   `json:"upn"`
	EmailVerified     bool     `json:"email_verified"`
	Name              string   `json:"name"`
	Groups            []string `json:"groups"`
	PreferredUsername string   `json:"preferred_username"`
	GivenName         string   `json:"given_name"`
	FamilyName        string   `json:"family_name"`
	Email             string   `json:"email"`
	ClientID          string   `json:"client_id"`
	Username          string   `json:"username"`
	TokenType         string   `json:"token_type"`
	Active            bool     `json:"active"`
	Website           string   `json:"website"`
	Organisations     []string `json:"org"`
}

IntrospectionResponse represents the fields returned by an RFC 7662 token introspection response, including some common provider extensions.

func (*IntrospectionResponse) Validate

func (c *IntrospectionResponse) Validate(_ context.Context) error

Validate satisfies the validator interface for IntrospectionResponse.

type KeycloakEndpoint

type KeycloakEndpoint struct {
	// contains filtered or unexported fields
}

KeycloakEndpoint represents a Keycloak OpenID Connect server endpoint.

func NewKeycloakEndpoint

func NewKeycloakEndpoint(baseURLStr string) (*KeycloakEndpoint, error)

NewKeycloakEndpoint creates a KeycloakEndpoint for the Keycloak server at baseURLStr.

func (*KeycloakEndpoint) RealmEndpoint

func (e *KeycloakEndpoint) RealmEndpoint(realm string, opts ...EndpointOption) (Endpoint, error)

RealmEndpoint returns the Endpoint for the given realm on this Keycloak server.

type OpenIDConfiguration

type OpenIDConfiguration struct {
	Issuer                                                    string   `json:"issuer"`
	AuthorizationEndpoint                                     string   `json:"authorization_endpoint"`
	TokenEndpoint                                             string   `json:"token_endpoint"`
	UserinfoEndpoint                                          string   `json:"userinfo_endpoint"`
	JWKSURI                                                   string   `json:"jwks_uri"`
	RegistrationEndpoint                                      string   `json:"registration_endpoint"`
	ScopesSupported                                           []string `json:"scopes_supported"`
	ResponseTypesSupported                                    []string `json:"response_types_supported"`
	GrantTypesSupported                                       []string `json:"grant_types_supported"`
	SubjectTypesSupported                                     []string `json:"subject_types_supported"`
	IDTokenSigningAlgValuesSupported                          []string `json:"id_token_signing_alg_values_supported"`
	TokenEndpointAuthMethodsSupported                         []string `json:"token_endpoint_auth_methods_supported"`
	ClaimsSupported                                           []string `json:"claims_supported"`
	CodeChallengeMethodsSupported                             []string `json:"code_challenge_methods_supported"`
	IntrospectionEndpoint                                     string   `json:"introspection_endpoint"`
	EndSessionEndpoint                                        string   `json:"end_session_endpoint"`
	FrontchannelLogoutSessionSupported                        bool     `json:"frontchannel_logout_session_supported"`
	FrontchannelLogoutSupported                               bool     `json:"frontchannel_logout_supported"`
	CheckSessionIframe                                        string   `json:"check_session_iframe"`
	AcrValuesSupported                                        []string `json:"acr_values_supported"`
	IDTokenEncryptionAlgValuesSupported                       []string `json:"id_token_encryption_alg_values_supported"`
	IDTokenEncryptionEncValuesSupported                       []string `json:"id_token_encryption_enc_values_supported"`
	UserinfoSigningAlgValuesSupported                         []string `json:"userinfo_signing_alg_values_supported"`
	UserinfoEncryptionAlgValuesSupported                      []string `json:"userinfo_encryption_alg_values_supported"`
	UserinfoEncryptionEncValuesSupported                      []string `json:"userinfo_encryption_enc_values_supported"`
	RequestObjectSigningAlgValuesSupported                    []string `json:"request_object_signing_alg_values_supported"`
	RequestObjectEncryptionAlgValuesSupported                 []string `json:"request_object_encryption_alg_values_supported"`
	RequestObjectEncryptionEncValuesSupported                 []string `json:"request_object_encryption_enc_values_supported"`
	ResponseModesSupported                                    []string `json:"response_modes_supported"`
	TokenEndpointAuthSigningAlgValuesSupported                []string `json:"token_endpoint_auth_signing_alg_values_supported"`
	IntrospectionEndpointAuthMethodsSupported                 []string `json:"introspection_endpoint_auth_methods_supported"`
	IntrospectionEndpointAuthSigningAlgValuesSupported        []string `json:"introspection_endpoint_auth_signing_alg_values_supported"`
	AuthorizationSigningAlgValuesSupported                    []string `json:"authorization_signing_alg_values_supported"`
	AuthorizationEncryptionAlgValuesSupported                 []string `json:"authorization_encryption_alg_values_supported"`
	AuthorizationEncryptionEncValuesSupported                 []string `json:"authorization_encryption_enc_values_supported"`
	ClaimTypesSupported                                       []string `json:"claim_types_supported"`
	ClaimsParameterSupported                                  bool     `json:"claims_parameter_supported"`
	RequestParameterSupported                                 bool     `json:"request_parameter_supported"`
	RequestURIParameterSupported                              bool     `json:"request_uri_parameter_supported"`
	RequireRequestURIRegistration                             bool     `json:"require_request_uri_registration"`
	TLSClientCertificateBoundAccessTokens                     bool     `json:"tls_client_certificate_bound_access_tokens"`
	RevocationEndpoint                                        string   `json:"revocation_endpoint"`
	RevocationEndpointAuthMethodsSupported                    []string `json:"revocation_endpoint_auth_methods_supported"`
	RevocationEndpointAuthSigningAlgValuesSupported           []string `json:"revocation_endpoint_auth_signing_alg_values_supported"`
	BackchannelLogoutSupported                                bool     `json:"backchannel_logout_supported"`
	BackchannelLogoutSessionSupported                         bool     `json:"backchannel_logout_session_supported"`
	DeviceAuthorizationEndpoint                               string   `json:"device_authorization_endpoint"`
	BackchannelTokenDeliveryModesSupported                    []string `json:"backchannel_token_delivery_modes_supported"`
	BackchannelAuthenticationEndpoint                         string   `json:"backchannel_authentication_endpoint"`
	BackchannelAuthenticationRequestSigningAlgValuesSupported []string `json:"backchannel_authentication_request_signing_alg_values_supported"`
	RequirePushedAuthorizationRequests                        bool     `json:"require_pushed_authorization_requests"`
	PushedAuthorizationRequestEndpoint                        string   `json:"pushed_authorization_request_endpoint"`
	MTLSEndpointAliases                                       struct {
		TokenEndpoint                      string `json:"token_endpoint"`
		RevocationEndpoint                 string `json:"revocation_endpoint"`
		IntrospectionEndpoint              string `json:"introspection_endpoint"`
		DeviceAuthorizationEndpoint        string `json:"device_authorization_endpoint"`
		RegistrationEndpoint               string `json:"registration_endpoint"`
		UserinfoEndpoint                   string `json:"userinfo_endpoint"`
		PushedAuthorizationRequestEndpoint string `json:"pushed_authorization_request_endpoint"`
		BackchannelAuthenticationEndpoint  string `json:"backchannel_authentication_endpoint"`
	} `json:"mtls_endpoint_aliases"`
	AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported"`
}

OpenIDConfiguration represents metadata returned by the OIDC discovery document.

type ProviderConfig

type ProviderConfig struct {
	ClientID     string `json:"client_id"     mapstructure:"client-id"`
	ClientSecret string `json:"client_secret" mapstructure:"client-secret"`
	Callback     string `json:"callback"      mapstructure:"callback"`
	// Scopes is optional and only used by browser/login-oriented integrations.
	Scopes []string `json:"scopes,omitzero" mapstructure:"scopes,omitzero"`
	// DiscoveryURL is optional and allows overriding provider discovery behavior
	// in integrations that support explicit discovery endpoints.
	DiscoveryURL string `json:"discovery_url,omitzero" mapstructure:"discovery-url,omitzero"`
}

ProviderConfig represents a single web provider configuration for Goth callbacks.

type ProviderMap

type ProviderMap map[string]ProviderConfig

ProviderMap indexes provider configurations by name.

type RefreshingClientCredentialsTokenSource

type RefreshingClientCredentialsTokenSource struct {
	// contains filtered or unexported fields
}

RefreshingClientCredentialsTokenSource is an oauth2.TokenSource that fetches a client_credentials token on first use and transparently refreshes it once it expires.

func (*RefreshingClientCredentialsTokenSource) Token

Token returns the current client_credentials token, fetching or refreshing it first if needed.

type RequestOpt

type RequestOpt func(url.Values)

RequestOpt mutates the form values of a token request before it is sent.

func WithAudience

func WithAudience(audience string) RequestOpt

WithAudience sets the "audience" form parameter on a token request, when audience is non-empty.

type TokenSourceFactory

type TokenSourceFactory func(cfg ClientConfig) (oauth2.TokenSource, error)

TokenSourceFactory creates a token source from config.

type TokenStore

type TokenStore interface {
	LoadToken(ctx context.Context) (*oauth2.Token, error)
	SaveToken(ctx context.Context, token *oauth2.Token) error
}

TokenStore abstracts token persistence.

type TokenValidator

type TokenValidator = jwt.TokenValidator

TokenValidator is an alias for jwt.TokenValidator.

type TrustConfig

type TrustConfig struct {
	Verifiers []ValidatorConfig `json:"validators" mapstructure:"validators"`
}

TrustConfig describes a set of validators that must all succeed.

type ValidatorConfig

type ValidatorConfig struct {
	EndpointConfig `mapstructure:",squash"`

	Audiences           []string       `json:"audiences"                  mapstructure:"audiences"`
	Issuer              string         `json:"issuer"                     mapstructure:"issuer"`
	CacheTTL            int            `json:"cache_ttl_seconds"          mapstructure:"cache_ttl_seconds"`
	SignatureAlgorithm  string         `json:"signature_algorithm"        mapstructure:"signature_algorithm"`
	SignatureAlgorithms []string       `json:"signature_algorithms"       mapstructure:"signature_algorithms"`
	AllowedClockSkew    int            `json:"allowed_clock_skew_seconds" mapstructure:"allowed_clock_skew_seconds"`
	Debug               bool           `json:"debug"                      mapstructure:"debug"`
	ClaimPredicate      map[string]any `json:"claim_predicates"           mapstructure:"claim_predicates"`
	// HMACSecret is an optional shared secret for HS256/HS384/HS512 token
	// validation. When non-empty, JWKS discovery is skipped and the secret is
	// used directly as the signing key. Intended for local development and
	// smoke testing only; never use a static shared secret in production.
	// Requires AllowInsecureHMAC: true to prevent accidental production use.
	HMACSecret string `json:"hmac_secret,omitempty" mapstructure:"hmac_secret"`

	// AllowInsecureHMAC must be set to true when HMACSecret is used. This
	// explicit opt-in acknowledges that HMAC shared secrets are not suitable
	// for production deployments. Never set this to true in production config.
	AllowInsecureHMAC bool `json:"allow_insecure_hmac,omitempty" mapstructure:"allow_insecure_hmac"`
}

ValidatorConfig controls validation behavior for issued tokens.

type ValidatorOpt

type ValidatorOpt func(*validatorOptions)

ValidatorOpt configures validator creation.

func WithValidatorCustomClaimsFactory added in v0.5.5

func WithValidatorCustomClaimsFactory(factory func() validator.CustomClaims) ValidatorOpt

WithValidatorCustomClaimsFactory sets a custom claims factory for the validator. When set, the validator will deserialize JWT payloads into the type returned by the factory, enabling provider-specific PrincipalSource implementations to extract typed claims from the context.

func WithValidatorJWKSProvider

func WithValidatorJWKSProvider(provider *jwks.CachingProvider) ValidatorOpt

WithValidatorJWKSProvider sets a custom JWKS caching provider.

func WithValidatorKeyFunc

func WithValidatorKeyFunc(keyFunc func(context.Context) (any, error)) ValidatorOpt

WithValidatorKeyFunc sets a custom key function for validation.

Directories

Path Synopsis
Package aws provides functionality to retrieve OIDC tokens from AWS STS GetWebIdentityToken API.
Package aws provides functionality to retrieve OIDC tokens from AWS STS GetWebIdentityToken API.
Package flyio provides an OIDC token source and principal extraction for Fly.io Machines, using tokens issued via Fly.io's local metadata socket.
Package flyio provides an OIDC token source and principal extraction for Fly.io Machines, using tokens issued via Fly.io's local metadata socket.
Package githubactions provides an OIDC token source and principal extraction for GitHub Actions workflows, using the workflow's ACTIONS_ID_TOKEN_REQUEST_URL to fetch tokens.
Package githubactions provides an OIDC token source and principal extraction for GitHub Actions workflows, using the workflow's ACTIONS_ID_TOKEN_REQUEST_URL to fetch tokens.
Package oidcutil provides shared helpers for provider-specific OIDC PrincipalSource implementations: flattening typed custom claims into a generic map, and the typed-path/generic-fallback-path pattern common to every provider in this module.
Package oidcutil provides shared helpers for provider-specific OIDC PrincipalSource implementations: flattening typed custom claims into a generic map, and the typed-path/generic-fallback-path pattern common to every provider in this module.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL