Documentation
¶
Overview ¶
Package oidc provides an OpenID Connect (OIDC) client and utilities for token validation and management.
Index ¶
- Constants
- Variables
- func ClaimsFromContext(ctx context.Context) any
- func DefaultTokenSourceFactories() map[string]TokenSourceFactory
- func DeviceCodeUIConsoleQR(deviceCode *oauth2.DeviceAuthResponse) error
- func DeviceCodeUIConsoleText(deviceCode *oauth2.DeviceAuthResponse) error
- func ExtractClaims[T jwtvalidator.CustomClaims](claims any) (jwtvalidator.RegisteredClaims, T, error)
- func KeyFetchingIssuers(validators []ValidatorConfig) []string
- func NewHTTPClientFromConfig(cfg *ClientConfig) (*http.Client, error)
- func NewIdentityClient(ctx context.Context, identity ClientConfig, target tls.ClientConfig, ...) (*http.Client, error)
- func NewMultiValidatorFromConfig(configs []ValidatorConfig, opts ...validator.Option) (jwt.TokenValidator, error)
- func NewTokenSourceFromConfig(cfg ClientConfig) (oauth2.TokenSource, error)
- func NewTokenSourceFromConfigWithFactories(cfg ClientConfig, factories map[string]TokenSourceFactory, store TokenStore, ...) (oauth2.TokenSource, error)
- func NewValidatorDebugger(v jwt.TokenValidator) jwt.TokenValidator
- func NewValidatorFromConfig(cfg *ValidatorConfig) (jwt.TokenValidator, error)
- func NewValidatorFromConfigWithOptions(cfg *ValidatorConfig, opts ...ValidatorOpt) (jwt.TokenValidator, error)
- func NewWaitingTokenSource(ctx context.Context, source oauth2.TokenSource, ...) oauth2.TokenSource
- func NewWaitingTokenSourceFromConfig(ctx context.Context, cfg ClientConfig, interval, timeout time.Duration) (oauth2.TokenSource, error)
- func ProbeValidators(ctx context.Context, validators []ValidatorConfig, doer HTTPDoer) error
- func ResolveTokenFromFile(filePath string) (*oauth2.Token, error)
- func SaveTokenToFile(token *oauth2.Token, filePath string) error
- func WithCustomClaims[T jwtvalidator.CustomClaims](t T) func(e Endpoint)
- type AWSCustomClaims
- type Client
- func (c *Client) AuthorizationCodeRedirectFlow(ctx context.Context, state string, scopes []string, redirectURI string, ...) (string, error)
- func (c *Client) AuthorizationCodeToken(ctx context.Context, code string, redirectURI string, opts ...RequestOpt) (*oauth2.Token, error)
- func (c *Client) ClientCredentialsToken(ctx context.Context, opts ...RequestOpt) (*oauth2.Token, error)
- func (c *Client) ClientID() string
- func (c *Client) DeviceToken(ctx context.Context, scopes ...string) (*oauth2.Token, error)
- func (c *Client) EndSession(ctx context.Context, refreshToken string) error
- func (c *Client) Endpoint() Endpoint
- func (c *Client) GothProvider(callbackURL *url.URL, scopes ...string) (goth.Provider, error)
- func (c *Client) HTTPClient(ctx context.Context, t *oauth2.Token) (*http.Client, error)
- func (c *Client) IntrospectToken(ctx context.Context, token string) (*IntrospectionResponse, error)
- func (c *Client) RefreshToken(ctx context.Context, refreshToken string, opts ...RequestOpt) (*oauth2.Token, error)
- func (c *Client) RefreshingClientCredentialsToken(ctx context.Context, opts ...RequestOpt) (oauth2.TokenSource, error)
- func (c *Client) TokenSource(t *oauth2.Token) (oauth2.TokenSource, error)
- func (c *Client) ValidateToken(ctx context.Context, token string, audiences []string) (*jwtvalidator.ValidatedClaims, error)
- type ClientConfig
- type ClientOpt
- func WithClientID(clientID string) ClientOpt
- func WithClientIDAndSecret(clientID, clientSecret string) ClientOpt
- func WithClock(clock Clock) ClientOpt
- func WithDeviceCodeUI(ui DeviceCodeUI) ClientOpt
- func WithHTTPClient(doer HTTPDoer) ClientOpt
- func WithJWKSProvider(provider *jwks.CachingProvider) ClientOpt
- func WithKeyCacheTTL(ttl time.Duration) ClientOpt
- func WithKeyFunc(keyFunc func(context.Context) (any, error)) ClientOpt
- func WithValidatingSignatureAlgorithm(algorithm jwtvalidator.SignatureAlgorithm) ClientOpt
- func WithValidatingSignatureAlgorithms(algorithms []jwtvalidator.SignatureAlgorithm) ClientOpt
- type Clock
- type Config
- type DeviceCodeUI
- type Endpoint
- func NewEndpoint(baseURL string, opts ...EndpointOption) (Endpoint, error)
- func NewEndpointFromConfig(config *EndpointConfig, opts ...EndpointOption) (Endpoint, error)
- func NewGitHubActionsEndpoint(baseURL string) (Endpoint, error)
- func NewGitHubEndpoint(baseURL string) (Endpoint, error)
- func NewKeycloakRealmEndpoint(baseURLStr, realm string, opts ...EndpointOption) (Endpoint, error)
- type EndpointConfig
- type EndpointOption
- type FileTokenStore
- type FlyIOCustomClaims
- type GitHubActionsCustomClaims
- type GitHubActionsEndpoint
- func (e *GitHubActionsEndpoint) DiscoveredConfiguration(ctx context.Context) (*OpenIDConfiguration, error)
- func (e *GitHubActionsEndpoint) DiscoveryEndpoint() (*url.URL, error)
- func (e *GitHubActionsEndpoint) OAuth2Endpoint(ctx context.Context) (oauth2.Endpoint, error)
- func (e *GitHubActionsEndpoint) URL() *url.URL
- type GitHubEndpoint
- func (e *GitHubEndpoint) DiscoveredConfiguration(_ context.Context) (*OpenIDConfiguration, error)
- func (e *GitHubEndpoint) DiscoveryEndpoint() (*url.URL, error)
- func (e *GitHubEndpoint) GothProvider(clientID, clientSecret string, callbackURL *url.URL, scopes ...string) (goth.Provider, error)
- func (e *GitHubEndpoint) OAuth2Endpoint(_ context.Context) (oauth2.Endpoint, error)
- func (e *GitHubEndpoint) URL() *url.URL
- type GothEndpoint
- type HTTPDoer
- type IdentityClientOption
- type IntrospectionResponse
- type KeycloakEndpoint
- type OpenIDConfiguration
- type ProviderConfig
- type ProviderMap
- type RefreshingClientCredentialsTokenSource
- type RequestOpt
- type TokenSourceFactory
- type TokenStore
- type TokenValidator
- type TrustConfig
- type ValidatorConfig
- type ValidatorOpt
- func WithValidatorBaseOptions(opts ...validator.Option) ValidatorOpt
- func WithValidatorCustomClaimsFactory(factory func() validator.CustomClaims) ValidatorOpt
- func WithValidatorJWKSProvider(provider *jwks.CachingProvider) ValidatorOpt
- func WithValidatorKeyFunc(keyFunc func(context.Context) (any, error)) ValidatorOpt
Examples ¶
Constants ¶
const ( ProviderTypeGitHub = "github" ProviderTypeGitHubActions = "githubactions" ProviderTypeKeycloak = "keycloak" ProviderTypeFlyIO = "flyio" ProviderTypeAWS = "aws" )
Recognised EndpointConfig.Type values.
const DefaultIdentityClientTimeout = 10 * time.Second
DefaultIdentityClientTimeout is the request timeout of clients built by NewIdentityClient, unless WithTimeout says otherwise.
Variables ¶
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.
var ErrClientSecretConflict = errors.New("client-secret and client-secret-file are mutually exclusive")
ErrClientSecretConflict is returned when both client-secret and client-secret-file are set on a ClientConfig.
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
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 KeyFetchingIssuers ¶ added in v0.16.0
func KeyFetchingIssuers(validators []ValidatorConfig) []string
KeyFetchingIssuers returns the distinct issuers whose signing keys the validators discover, resolving each the way dioad/auth's validator does: the configured issuer, else the endpoint URL. HMAC validators use a static secret and fetch nothing.
func NewHTTPClientFromConfig ¶
func NewHTTPClientFromConfig(cfg *ClientConfig) (*http.Client, error)
NewHTTPClientFromConfig creates an HTTP client with a token source from a ClientConfig.
func NewIdentityClient ¶ added in v0.15.0
func NewIdentityClient(ctx context.Context, identity ClientConfig, target tls.ClientConfig, opts ...IdentityClientOption) (*http.Client, error)
NewIdentityClient returns an HTTP client that authenticates as identity (OAuth2 client credentials, a platform workload identity, or a token file) when identity is set, and a plain client when identity is the zero value.
target configures TLS to the service being called. identity.TLSClient configures TLS to the identity provider's discovery and token endpoints. It has no effect for the platform identity types "aws", "githubactions" and "flyio", which fetch their tokens from the platform rather than a provider this client reaches.
Tokens are fetched lazily, on the first request and again when they expire. Those fetches keep ctx's values but not its cancellation, so the client outlives a ctx that is cancelled once start-up is done.
Example ¶
ExampleNewIdentityClient builds the HTTP client one service uses to call another. With an identity it authenticates as that identity, here with the OAuth2 client credentials grant. With the zero identity it is a plain client, which suits local development against a service without auth.
The helpers below stand in for the identity provider and the service being called.
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"github.com/dioad/net/tls"
"github.com/dioad/util"
"github.com/dioad/auth/oidc"
)
// ExampleNewIdentityClient builds the HTTP client one service uses to call
// another. With an identity it authenticates as that identity, here with the
// OAuth2 client credentials grant. With the zero identity it is a plain
// client, which suits local development against a service without auth.
//
// The helpers below stand in for the identity provider and the service being
// called.
func main() {
service := newEchoAuthService(httptest.NewServer)
defer service.Close()
provider := newTokenProvider(httptest.NewServer)
defer provider.server.Close()
ctx := context.Background()
plain, err := oidc.NewIdentityClient(ctx, oidc.ClientConfig{}, tls.ClientConfig{})
if err != nil {
fmt.Println(err)
return
}
_, header, _ := get(ctx, plain, service.URL)
fmt.Printf("plain client sends: %q\n", header)
// provider.identity() is an oidc.ClientConfig with the provider's URL, a
// client ID and a client secret.
authenticated, err := oidc.NewIdentityClient(ctx, provider.identity(), tls.ClientConfig{})
if err != nil {
fmt.Println(err)
return
}
_, header, _ = get(ctx, authenticated, service.URL)
fmt.Printf("identity client sends: %q\n", header)
}
// tokenProvider is an identity provider that issues "service-token" for the
// client credentials grant and counts how many tokens it has issued.
type tokenProvider struct {
server *httptest.Server
issued atomic.Int32
}
// newTokenProvider starts a tokenProvider using newServer, which is
// httptest.NewServer or httptest.NewTLSServer.
func newTokenProvider(newServer func(http.Handler) *httptest.Server) *tokenProvider {
p := &tokenProvider{}
mux := http.NewServeMux()
p.server = newServer(mux)
mux.HandleFunc("GET /.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"issuer": p.server.URL,
"token_endpoint": p.server.URL + "/token",
})
})
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
if r.PostFormValue("grant_type") != "client_credentials" || r.PostFormValue("client_secret") != "service-secret" {
http.Error(w, "invalid_client", http.StatusUnauthorized)
return
}
p.issued.Add(1)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": "service-token",
"token_type": "Bearer",
"expires_in": 3600,
})
})
return p
}
func (p *tokenProvider) identity() oidc.ClientConfig {
return oidc.ClientConfig{
URL: p.server.URL,
ClientID: "billing-service",
ClientSecret: *util.NewMaskedString("service-secret"),
}
}
// newEchoAuthService starts a service that replies with the Authorization
// header it was sent.
func newEchoAuthService(newServer func(http.Handler) *httptest.Server) *httptest.Server {
return newServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprint(w, r.Header.Get("Authorization"))
}))
}
// get returns the status and body of a GET to url, or the request error.
func get(ctx context.Context, client *http.Client, url string) (int, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, "", err
}
resp, err := client.Do(req)
if err != nil {
return 0, "", err
}
defer func() { _ = resp.Body.Close() }()
var body [256]byte
n, _ := resp.Body.Read(body[:])
return resp.StatusCode, string(body[:n]), nil
}
Output: plain client sends: "" identity client sends: "Bearer service-token"
func NewMultiValidatorFromConfig ¶
func NewMultiValidatorFromConfig(configs []ValidatorConfig, opts ...validator.Option) (jwt.TokenValidator, error)
NewMultiValidatorFromConfig creates a MultiValidator from multiple configs. opts apply to every validator as base options (see WithValidatorBaseOptions), so a config or provider type that sets the same thing overrides them.
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 ProbeValidators ¶ added in v0.16.0
func ProbeValidators(ctx context.Context, validators []ValidatorConfig, doer HTTPDoer) error
ProbeValidators checks that every identity provider behind validators answers OIDC discovery and serves at least one signing key, using doer for the requests (nil means http.DefaultClient), and returns every failure joined. It returns nil when no validator fetches keys, so it is safe to call for any configuration; see KeyFetchingIssuers.
It is for a readiness check. A pass means each issuer was reachable just now; it does not prove the validators' own key caches are current.
func ResolveTokenFromFile ¶
ResolveTokenFromFile loads an OAuth2 token from a file. A file that holds neither an access token nor a refresh token, such as an empty one, is an error rather than an empty token.
func SaveTokenToFile ¶
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 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
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 ¶
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) EndSession ¶ added in v0.14.7
EndSession ends the user's session at the provider from the server, by posting refreshToken with the client's credentials to the end_session endpoint. Keycloak accepts this from a confidential client and ends the user's single sign-on session, so the next sign-in asks for credentials again instead of completing silently. It is Keycloak's back-channel form, not OpenID Connect RP-Initiated Logout, which is driven by the browser.
func (*Client) Endpoint ¶
Endpoint returns the OIDC provider endpoint this Client was constructed with.
func (*Client) GothProvider ¶
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 ¶
HTTPClient returns an *http.Client that attaches t as a bearer token, refreshing it via the OAuth2 flow when it expires.
func (*Client) IntrospectToken ¶
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 ¶
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 is the OAuth 2.0 client identifier registered with the provider.
ClientID string `json:"client_id" mapstructure:"client-id"`
// ClientSecret is the OAuth 2.0 client secret, used for the client
// credentials flow. Set at most one of ClientSecret and ClientSecretFile.
ClientSecret util.MaskedString `json:"client_secret" mapstructure:"client-secret,omitempty"`
// ClientSecretFile is the path to a file containing the client secret, for
// example a mounted container secret. Surrounding whitespace is trimmed.
// The file is read when the token source is built, not when the config is
// validated; an unreadable or empty file is an error. Set at most one of
// ClientSecret and ClientSecretFile.
ClientSecretFile string `json:"client_secret_file,omitempty" mapstructure:"client-secret-file,omitempty"`
// Audience is the audience requested for issued tokens. It is required by
// platform identity providers such as "githubactions", "flyio" and "aws"
// and ignored by providers that do not support it.
Audience string `json:"audience,omitempty" mapstructure:"audience,omitempty"`
// TokenFile is the path to a file used to persist the interactive login
// token between runs. When set, the token is loaded from the file and
// refreshed with its refresh token once it expires.
TokenFile string `json:"token_file,omitempty" mapstructure:"token-file,omitempty"`
// TLSClient configures TLS for connections to the provider, such as a
// custom CA bundle.
TLSClient tls.ClientConfig `json:"tls_client" mapstructure:"tls-client,omitempty"`
}
ClientConfig captures client credentials and token acquisition options for an OIDC provider.
func (*ClientConfig) Check ¶ added in v0.15.0
func (c *ClientConfig) Check(findings *configcheck.Collector)
Check reports the problems Validate finds in the client secret settings to findings, which should be positioned at the OIDC client block, so a service reports them with the rest of its config's problems at their full path. The conflict is reported at client-secret-file. Like Validate, it does not read the file.
Example ¶
package main
import (
"fmt"
"github.com/dioad/config/configcheck"
"github.com/dioad/util"
"github.com/dioad/auth/oidc"
)
func main() {
cfg := oidc.ClientConfig{
ClientSecret: *util.NewMaskedString("s3cret"),
ClientSecretFile: "/run/secrets/oidc",
}
findings := configcheck.NewCollector()
cfg.Check(findings.Field("identity"))
for _, f := range findings.Findings() {
fmt.Println(f)
}
}
Output: identity.client-secret-file: client-secret and client-secret-file are mutually exclusive
func (*ClientConfig) ResolveClientSecret ¶ added in v0.14.0
func (c *ClientConfig) ResolveClientSecret() (string, error)
ResolveClientSecret returns the client secret, reading ClientSecretFile when it is set. Surrounding whitespace in the file is trimmed. It returns an empty string and no error when neither client-secret nor client-secret-file is set.
func (*ClientConfig) Validate ¶ added in v0.14.0
func (c *ClientConfig) Validate() error
Validate reports configuration errors that can be detected without touching the filesystem. It deliberately does not read ClientSecretFile, because a mounted secret may not exist on the host that validates the config.
type ClientOpt ¶
type ClientOpt func(c *Client)
ClientOpt configures an OIDC Client.
func WithClientID ¶
WithClientID sets the client identifier used for OIDC flows.
func WithClientIDAndSecret ¶
WithClientIDAndSecret sets both the client ID and secret for the client.
func WithDeviceCodeUI ¶
func WithDeviceCodeUI(ui DeviceCodeUI) ClientOpt
WithDeviceCodeUI injects a custom device code UI handler for interactive flows.
func WithHTTPClient ¶
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 ¶
WithKeyCacheTTL overrides the cache TTL for JWKS keys used during validation.
func WithKeyFunc ¶
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 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, opts ...EndpointOption) (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. opts apply to the endpoint types that take options: every type except github and githubactions.
func NewGitHubActionsEndpoint ¶
NewGitHubActionsEndpoint creates a new GitHub Actions OIDC endpoint.
func NewGitHubEndpoint ¶
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 selects a provider-specific behaviour. Accepted values are "github",
// "githubactions", "keycloak", "flyio" and "aws". Leave empty for a
// generic OIDC provider discovered from URL.
Type string `json:"type,omitempty" mapstructure:"type,omitempty"`
// URL is the OIDC issuer URL, for example "https://accounts.example.com".
// Provider metadata and signing keys are discovered from it.
URL string `json:"url" mapstructure:"url"`
// KeycloakRealm is the Keycloak realm name. It is only used when Type is
// "keycloak".
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.
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 ¶
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 ¶
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 IdentityClientOption ¶ added in v0.15.0
type IdentityClientOption func(*identityClientOptions)
IdentityClientOption configures NewIdentityClient.
func WithBaseTransport ¶ added in v0.15.0
func WithBaseTransport(transport *http.Transport) IdentityClientOption
WithBaseTransport sets the transport that calls are sent through. It is cloned before any TLS configuration is applied, so the caller's transport is never modified. The default is a clone of http.DefaultTransport.
func WithTimeout ¶ added in v0.15.0
func WithTimeout(timeout time.Duration) IdentityClientOption
WithTimeout sets the request timeout for calls to the target service and to the token endpoint. Zero means no timeout.
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) UnmarshalJSON ¶ added in v0.14.6
func (c *IntrospectionResponse) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes an introspection response or a JWT's claims. "aud" may be a string or, as in a JWT for several audiences, a list, of which Audience keeps the first.
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.
type RequestOpt ¶
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.
func WithPrompt ¶ added in v0.14.7
func WithPrompt(prompt string) RequestOpt
WithPrompt sets the "prompt" parameter on an authorization request, when prompt is non-empty. "create" asks the provider to show its registration form instead of sign-in (OpenID Connect Prompt Create 1.0).
func WithScope ¶ added in v0.12.0
func WithScope(scope string) RequestOpt
WithScope sets the "scope" form parameter on a token request, when scope is non-empty. For multiple scopes, pass a single space-delimited string, per the OAuth2 spec.
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 lists the accepted values of the token "aud" claim. A token is
// accepted if it carries at least one of them.
Audiences []string `json:"audiences" mapstructure:"audiences"`
// Issuer is the expected token "iss" claim. Signing keys are discovered
// from its JWKS endpoint.
Issuer string `json:"issuer" mapstructure:"issuer"`
// CacheTTL is how long, in seconds, discovered signing keys are cached.
// Defaults to 300 when unset or not positive.
CacheTTL int `json:"cache_ttl_seconds" mapstructure:"cache_ttl_seconds"`
// SignatureAlgorithm is a single accepted signing algorithm, for example
// "RS256". Ignored when SignatureAlgorithms is set.
SignatureAlgorithm string `json:"signature_algorithm" mapstructure:"signature_algorithm"`
// SignatureAlgorithms lists the accepted signing algorithms, for example
// ["RS256", "ES256"]. Takes precedence over SignatureAlgorithm.
SignatureAlgorithms []string `json:"signature_algorithms" mapstructure:"signature_algorithms"`
// AllowedClockSkew is the tolerance, in seconds, applied to the token
// "exp", "nbf" and "iat" claims. Defaults to 60 when unset or not positive.
AllowedClockSkew int `json:"allowed_clock_skew_seconds" mapstructure:"allowed_clock_skew_seconds"`
// Debug enables debug logging of each token validation attempt and its
// outcome. Intended for troubleshooting.
Debug bool `json:"debug" mapstructure:"debug"`
// ClaimPredicate restricts which tokens are accepted by their claims. Each
// key is a claim name and its value is the required claim value; an array
// claim matches when it contains the value. All entries must match. Use
// the reserved keys "and" and "or", each holding a list of such maps, for
// nested combinations.
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 WithValidatorBaseOptions ¶ added in v0.14.6
func WithValidatorBaseOptions(opts ...validator.Option) ValidatorOpt
WithValidatorBaseOptions adds go-jwt-middleware validator options that apply unless the config or the provider type sets the same thing: they are applied first. For example, validator.WithCustomClaims here sets the claims type for a generic OIDC issuer while a "flyio" issuer keeps *flyio.Claims.
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.
Source Files
¶
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. |