oidc

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 27 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package oidc implements a stateless OIDC 1.0 Relying Party running the Authorization Code flow with PKCE. On a successful callback the verified principal is handed to the consumer via a gosso.OnAuthenticated callback; this package never writes session cookies itself. A short lived, signed transit cookie is used purely to carry state, nonce and the PKCE verifier between /login and /callback.

The post-login redirect defaults to the ?target= carried through the transit cookie. WithOnRedirect lets the consumer compute the final destination — it sees the resolved target (which OnAuthenticated does not) and owns the ResponseWriter, so it can branch on where login was initiated and set additional cookies before the redirect.

Index

Constants

View Source
const StageIDPError = "idp-error"

StageIDPError is the stage OnLoginError receives when the IdP redirected back with ?error= (for example access_denied after a user cancelled).

Variables

View Source
var ErrRefreshRejected = errors.New("oidc: refresh token rejected")

ErrRefreshRejected means the IdP answered the refresh grant with invalid_grant: the refresh token is expired, revoked or unknown, and the session it backs is over.

View Source
var ErrRefreshSubjectMismatch = errors.New("oidc: refreshed subject mismatch")

ErrRefreshSubjectMismatch means the IdP granted the refresh but the identity it returned is not the expected one: the refreshed subject differs from expectedExternalID or lacks the external-id claim, or UserInfo's sub differs from the ID token's. Retrying cannot fix it, so treat the session as over. It always comes wrapped in a *RefreshFailedError.

View Source
var StandardClaimMap = ClaimMap{
	ExternalID: "sub",
	Email:      "email",
	Firstname:  "given_name",
	Lastname:   "family_name",
	Groups:     "groups",
}

StandardClaimMap is the default mapping suitable for most OIDC IdPs (Keycloak, Okta, Auth0, Microsoft Entra ID with the `groups` claim enabled).

Functions

This section is empty.

Types

type ClaimMap

type ClaimMap struct {
	ExternalID string
	Email      string
	Firstname  string
	Lastname   string
	Groups     string
}

ClaimMap names the OIDC claims that are copied into sso.Subject's common fields. The defaults target the core + profile + email scopes plus the widely-used `groups` claim.

type Handlers

type Handlers struct {
	Login    http.Handler
	Callback http.Handler
	Logout   http.Handler
}

Handlers groups the three HTTP handlers the consumer mounts on its router: Login initiates the flow, Callback completes the code exchange, Logout fires OnLogout and (optionally) redirects to the IdP's end-session endpoint.

type LoginContext added in v0.5.0

type LoginContext map[string]string

LoginContext is consumer-defined data carried, signed but not encrypted, in the transit cookie from login start to the callback hooks. Never put secrets in it: the browser can read it.

func LoginContextFromContext added in v0.5.0

func LoginContextFromContext(ctx context.Context) (LoginContext, bool)

LoginContextFromContext returns the login context of the login being completed. It is set inside OnAuthenticated and OnRedirect when the login was started with WithLoginContext. The result is a copy.

type LoginOption added in v0.5.0

type LoginOption = options.Option[*loginOptions]

LoginOption configures a single login started with RP.Login.

func WithLoginContext added in v0.5.0

func WithLoginContext(lc LoginContext) LoginOption

WithLoginContext attaches lc to the login. OnAuthenticated, OnRedirect and OnLoginError see it again on the callback. The map is cloned; nil or empty means no context.

func WithLoginInitError added in v0.5.0

func WithLoginInitError(fn func(w http.ResponseWriter, r *http.Request, err error)) LoginOption

WithLoginInitError replaces the default 500 response when the login cannot start (transit cookie too large). fn owns the response; nothing has been written yet.

func WithLoginScopes added in v0.5.0

func WithLoginScopes(scopes ...string) LoginOption

WithLoginScopes requests scopes for this login on top of the RP's own (WithScopes, WithExtraScopes). Use it for a scope only some logins need, such as offline_access for the native broker: requested on every login, it would open an offline session at the IdP for each web login too.

func WithLoginTarget added in v0.5.0

func WithLoginTarget(target string) LoginOption

WithLoginTarget sets the post-login target. Like ?target= on the login handler, it is sanitised: only app-local paths are kept, anything else becomes "/".

type LogoutHintProvider

type LogoutHintProvider func(*http.Request) string

LogoutHintProvider returns the raw ID token (typically extracted from the consumer's session) to be included as id_token_hint in an RP-initiated logout request. Returning an empty string skips the IdP-side SLO.

type OnLoginError added in v0.5.0

type OnLoginError func(
	ctx context.Context,
	w http.ResponseWriter,
	r *http.Request,
	lc LoginContext,
	stage string,
	err error,
) (redirect string)

OnLoginError runs when the callback fails after the transit cookie and state were verified, so lc is the login context of this very login. stage names the failing step (StageIDPError, "token-exchange", "on-redirect", ...); the IdP's own error code, if any, is in r.URL.Query().Get("error"). Returning a non-empty URL redirects there with 302. The URL is not sanitised: the consumer owns it. Returning "" keeps the default HTTP error response.

Failures before the state check (a missing, tampered or expired transit cookie, a state mismatch) never reach OnLoginError: the context is not trustworthy there.

type OnRedirect added in v0.2.0

type OnRedirect func(
	ctx context.Context,
	w http.ResponseWriter,
	r *http.Request,
	sub sso.Subject[Payload],
	target string,
) (finalTarget string, err error)

OnRedirect computes the post-login redirect destination. It runs after a successful OnAuthenticated, receiving the authenticated subject and the resolved (safe) target from the transit state. Returning a non-empty string overrides the redirect destination; returning "" keeps the default target. Returning an error aborts the callback. It owns the ResponseWriter, so a consumer may set additional cookies (e.g. rebinding a cart on login) before the redirect happens.

Keeping the redirect decision here — rather than inside OnAuthenticated — lets the consumer branch on where login was initiated (the target), which OnAuthenticated does not see.

type Option

type Option = options.OptionE[*RP]

Option configures an RP.

func WithBootstrapTimeout

func WithBootstrapTimeout(d time.Duration) Option

WithBootstrapTimeout bounds the time `New` will spend on OIDC discovery. Defaults to 30s. Values ≤ 0 are rejected.

func WithClaimMap

func WithClaimMap(m ClaimMap) Option

WithClaimMap overrides the default claim names used to populate sso.Subject.

func WithDiscoveryBaseURL added in v0.3.0

func WithDiscoveryBaseURL(discoveryBaseURL string) Option

WithDiscoveryBaseURL configures the client to work with a OpenID Connect server deployed at the same local cluster relaxing the requirement to use https as transport protocol but to use http instead for the discovery phase using discoveryBaseURL instead of issuerURL

func WithErrorLogger

func WithErrorLogger(fn sso.ErrorLogger) Option

WithErrorLogger routes runtime errors encountered by the OIDC handlers to the supplied logger. HTTP responses stay generic regardless; the logger sees the underlying cause.

func WithExtraScopes

func WithExtraScopes(scopes ...string) Option

WithExtraScopes appends scopes to the default {openid, profile, email} set, or to the set WithScopes replaced it with. Most commonly used to request `offline_access` for refresh tokens.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient overrides the client used for discovery, token and UserInfo calls. The default client has a 15 second Timeout; a client supplied here is used as-is — set your own Timeout if you want one.

func WithIssuerValidator

func WithIssuerValidator(fn func(iss string) error) Option

WithIssuerValidator overrides the default strict issuer check. Use this to accept e.g. Microsoft Entra ID's tenant-GUID issuer pattern. Passing nil restores the default (strict equality with the issuer URL).

WARNING: when a validator is configured, the underlying go-oidc verifier's issuer check is disabled and the validator is the only gate. A buggy validator that returns nil unconditionally silently accepts any issuer — write the validator with care. Example:

oidc.WithIssuerValidator(func(iss string) error {
    if strings.HasPrefix(iss, "https://login.microsoftonline.com/") &&
        strings.HasSuffix(iss, "/v2.0") {
        return nil
    }
    return fmt.Errorf("unexpected issuer: %s", iss)
})

func WithLogoutHintProvider

func WithLogoutHintProvider(fn LogoutHintProvider) Option

WithLogoutHintProvider configures the callback used by the logout handler to populate `id_token_hint` on the end-session URL.

func WithOnLoginError added in v0.5.0

func WithOnLoginError(fn OnLoginError) Option

WithOnLoginError registers a callback that may redirect on callback failures after the state check. See OnLoginError.

func WithOnLogout

func WithOnLogout(fn sso.OnLogout) Option

WithOnLogout registers a callback invoked before the RP-initiated logout redirect (if any).

func WithOnRedirect added in v0.2.0

func WithOnRedirect(fn OnRedirect) Option

WithOnRedirect registers a callback that computes the final post-login redirect target. See OnRedirect. When unset, the callback redirects to the transit target (or "/") unchanged.

func WithPostLogoutRedirectURL

func WithPostLogoutRedirectURL(u string) Option

WithPostLogoutRedirectURL sets the URL the IdP will redirect back to after a successful RP-initiated logout.

func WithScopes added in v0.3.0

func WithScopes(scopes ...string) Option

WithScopes replaces the default {openid, profile, email} scope set. `openid` is always requested, whether listed or not. Use it for an IdP that rejects the whole authorization request over a scope it does not offer — for example one without the `email` scope, whose email then arrives in a claim WithClaimMap has to name. WithExtraScopes still appends to the replaced set.

func WithTransitCookieName

func WithTransitCookieName(name string) Option

WithTransitCookieName overrides the default transit cookie name.

func WithTransitDeprecatedKeys

func WithTransitDeprecatedKeys(keys ...[]byte) Option

WithTransitDeprecatedKeys adds previously-used signing keys that are still accepted when verifying incoming transit cookies. Supports key rotation. Each key must meet the same minimum length as the primary.

func WithTransitTTL

func WithTransitTTL(d time.Duration) Option

WithTransitTTL overrides the default transit cookie lifetime (5 min).

func WithUserInfo

func WithUserInfo(enabled bool) Option

WithUserInfo enables a call to the UserInfo endpoint after the token exchange. Claims from UserInfo are merged into the result and override claims from the ID token on conflict. The UserInfo `sub` is verified to equal the ID token `sub` per OIDC Core §5.3.2 before merging.

type Payload

type Payload struct {
	// IDToken is the verified ID token. Treat as read-only: further
	// calls to Claims() decode into the caller's destination and are
	// otherwise side-effect free. Always set after a login; nil after
	// RP.Refresh when the IdP returned no ID token (OIDC Core §12.2), in
	// which case UserInfo carries the claims.
	IDToken *gooidc.IDToken
	// RawIDToken is the serialised JWT — useful as an id_token_hint on
	// RP-initiated logout, for forwarding, or for logging. Empty whenever
	// IDToken is nil.
	RawIDToken string
	// AccessToken is the OAuth2 access token returned by the token
	// endpoint. It may be empty if the IdP only issued an ID token.
	AccessToken string
	// TokenExpiry is the access token's expiry.
	TokenExpiry time.Time
	// RefreshToken is the OAuth2 refresh token, present only when the
	// `offline_access` scope was granted.
	RefreshToken string
	// UserInfo holds the raw claims from the UserInfo endpoint, set when
	// WithUserInfo(true) was supplied, or after RP.Refresh when the IdP
	// returned no ID token.
	UserInfo map[string]any
}

Payload is the OIDC-specific data carried in sso.Subject[Payload].Raw.

type RP

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

RP is a constructed OIDC Relying Party. Obtain one from New and mount the values returned by Handlers onto the consumer's router.

func New

func New(
	ctx context.Context,
	issuerURL string,
	clientID string,
	clientSecret string,
	redirectURL string,
	transitSigningKey []byte,
	onAuthenticated sso.OnAuthenticated[Payload],
	opts ...Option,
) (*RP, error)

New constructs an OIDC Relying Party. It performs OIDC discovery synchronously; a slow or unreachable IdP surfaces as an error here (bounded by the bootstrap timeout).

The mandatory parameters are:

  • ctx: context of the calling service
  • issuerURL: OIDC issuer; all endpoints are populated from `<issuer>/.well-known/openid-configuration` unless overridden. Must be HTTPS; loopback hosts are allowed over HTTP for local development.
  • clientID, clientSecret: confidential-client credentials.
  • redirectURL: callback URL matching the redirect_uri registered at the IdP. HTTPS required (loopback exception applies).
  • transitSigningKey: HMAC-SHA256 key used to sign the short-lived transit cookie carrying state, nonce and PKCE verifier. Minimum 32 bytes.
  • onAuthenticated: callback invoked after a successful code exchange + ID token verification.

func (*RP) Handlers

func (rp *RP) Handlers() Handlers

Handlers returns the RP's HTTP handlers.

func (*RP) Login added in v0.5.0

func (rp *RP) Login(w http.ResponseWriter, r *http.Request, opts ...LoginOption)

Login starts an authorization request: it generates fresh state, nonce and PKCE values, stores them with the target and login context in the signed transit cookie and redirects to the IdP. Handlers().Login is Login with the target taken from ?target=. Every login started here counts in the login telemetry, the native broker's included.

func (*RP) Refresh added in v0.5.0

func (rp *RP) Refresh(ctx context.Context, refreshToken, expectedExternalID string) (sso.Subject[Payload], error)

Refresh redeems an IdP refresh token. The returned subject is rebuilt from the refreshed ID token, or from UserInfo when the IdP returns none; its ExternalID must equal expectedExternalID. Payload.RefreshToken holds the token to store next (rotated, or the input when the IdP did not rotate). ErrRefreshRejected means the IdP answered invalid_grant (session over), and so does ErrRefreshSubjectMismatch; any other error is transient. A failure after the grant succeeded is a *RefreshFailedError carrying the refresh token to keep.

Refresh does not call the ErrorLogger: there is no request to log against, so the caller logs.

func (*RP) UnsupportedScopes added in v0.3.0

func (rp *RP) UnsupportedScopes() []string

UnsupportedScopes returns the requested scopes the IdP's discovery document does not list in scopes_supported, or nil when it lists them all or publishes no list. Log it at startup: an IdP may reject the whole authorization request over a single unoffered scope, and report that only on its own error page.

type RefreshFailedError added in v0.5.0

type RefreshFailedError struct {
	RefreshToken string
	Err          error
}

RefreshFailedError is returned by Refresh when the IdP granted the refresh but a later step failed (ID-token verification, UserInfo, subject check, ...). The IdP may already have retired the input token, so store RefreshToken (the token it issued, or the input when it did not rotate) before retrying. It is never ErrRefreshRejected; a subject mismatch (ErrRefreshSubjectMismatch) is the one failure not worth retrying.

func (*RefreshFailedError) Error added in v0.5.0

func (e *RefreshFailedError) Error() string

func (*RefreshFailedError) Unwrap added in v0.5.0

func (e *RefreshFailedError) Unwrap() error

Directories

Path Synopsis
Package native is an opt-in broker that lets native (mobile, desktop, CLI) public clients log in through an oidc.RP using OAuth 2.0 for native apps: RFC 6749 authorization code + RFC 7636 PKCE (S256 only), RFC 8252 redirect URIs and RFC 7009 revocation.
Package native is an opt-in broker that lets native (mobile, desktop, CLI) public clients log in through an oidc.RP using OAuth 2.0 for native apps: RFC 6749 authorization code + RFC 7636 PKCE (S256 only), RFC 8252 redirect URIs and RFC 7009 revocation.
repository
Package repository persists the native broker's one-time codes and refresh sessions.
Package repository persists the native broker's one-time codes and refresh sessions.
repository/store
Package store holds the entities the native broker persists through its repositories: one-time codes and refresh sessions.
Package store holds the entities the native broker persists through its repositories: one-time codes and refresh sessions.

Jump to

Keyboard shortcuts

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