Documentation
¶
Overview ¶
Package oidclient is an OIDC relying party library for web applications authenticating against an OpenID Connect provider (designed for use with infodancer/webauth but compatible with any spec-compliant IdP).
It wraps github.com/coreos/go-oidc/v3 for discovery, JWKS, and token verification, and golang.org/x/oauth2 for the authorization code flow with PKCE. Cookie helpers and a convenience API are layered on top.
Index ¶
- Constants
- Variables
- func ClearFlowCookies(w http.ResponseWriter)
- func ClearSessionCookie(w http.ResponseWriter, name string, secure bool)
- func FlowCookieValue(r *http.Request, name string) string
- func GenerateNonce() (string, error)
- func GenerateVerifier() string
- func GetOrCreateFlow(w http.ResponseWriter, r *http.Request, returnTo string) (state, verifier string, err error)
- func IsSecure(r *http.Request) bool
- func SetFlowCookie(w http.ResponseWriter, name, value string, secure bool)
- func SetSessionCookie(w http.ResponseWriter, name, token string, secure bool)
- type CallbackOptions
- type Claims
- type Client
- func (c *Client) AuthorizeURL(state, verifier string) string
- func (c *Client) CallbackHandler(opts CallbackOptions) http.Handler
- func (c *Client) ClientID() string
- func (c *Client) CookieName() string
- func (c *Client) Exchange(ctx context.Context, code, verifier string) (*Tokens, *Claims, error)
- func (c *Client) ExchangeCode(ctx context.Context, code, verifier string) (accessToken string, claims *Claims, err error)deprecated
- func (c *Client) FlowConfigured() bool
- func (c *Client) LoginURL(redirectPath string) string
- func (c *Client) LogoutURL() string
- func (c *Client) Ready() bool
- func (c *Client) Refresh(ctx context.Context, refreshToken string) (*Tokens, *Claims, error)
- func (c *Client) RegisterURL(state, verifier string) string
- func (c *Client) Validate(ctx context.Context, tokenStr string) (*Claims, error)
- func (c *Client) ValidateCookie(r *http.Request) (*Claims, error)
- type Config
- type Tokens
Constants ¶
const ( // Default cookie names for the OIDC authorization flow. CookieVerifier = "oauth_verifier" CookieState = "oauth_state" CookieRedirect = "oauth_redirect" )
Variables ¶
var ( ErrNoCookie = errors.New("oidclient: missing auth cookie") ErrNoIDToken = errors.New("oidclient: token response missing id_token") ErrMissingSub = errors.New("oidclient: token missing sub claim") ErrNoRefreshToken = errors.New("oidclient: no refresh token") // ErrNotReady is returned by token operations on a [NewLazy] client whose // provider discovery has not yet succeeded. Treat it as "anonymous" on // validation paths and as "sign-in temporarily unavailable" on flow paths. ErrNotReady = errors.New("oidclient: provider not ready") )
Sentinel errors returned by Validate, ValidateCookie, and ExchangeCode.
Functions ¶
func ClearFlowCookies ¶
func ClearFlowCookies(w http.ResponseWriter)
ClearFlowCookies expires all OIDC flow cookies.
func ClearSessionCookie ¶
func ClearSessionCookie(w http.ResponseWriter, name string, secure bool)
ClearSessionCookie expires the session cookie.
func FlowCookieValue ¶
FlowCookieValue reads a named cookie value, returning "" if absent.
func GenerateNonce ¶
GenerateNonce returns a random base64url-encoded state nonce for CSRF protection.
func GenerateVerifier ¶
func GenerateVerifier() string
GenerateVerifier returns a random PKCE code verifier (RFC 7636). The verifier should be stored (e.g. in a cookie) and passed to both AuthorizeURL and ExchangeCode.
func GetOrCreateFlow ¶ added in v0.2.0
func GetOrCreateFlow(w http.ResponseWriter, r *http.Request, returnTo string) (state, verifier string, err error)
GetOrCreateFlow returns the state and PKCE verifier for the current authorization flow, generating them and setting the flow cookies when no flow is in progress. An existing flow (both state and verifier cookies present) is reused, so concurrent unauthenticated requests share one flow instead of overwriting the state another in-flight redirect depends on. The redirect cookie is always set to returnTo: state and verifier are per-flow, the post-login destination follows the latest request.
func SetFlowCookie ¶
func SetFlowCookie(w http.ResponseWriter, name, value string, secure bool)
SetFlowCookie writes an HttpOnly cookie used during the OIDC flow. The cookie is session-lifetime: the flow must survive however long the user leaves the IdP's login page open, and the state/verifier nonces derive no security from a fixed expiry -- the authorization code and PKCE binding do.
func SetSessionCookie ¶
func SetSessionCookie(w http.ResponseWriter, name, token string, secure bool)
SetSessionCookie writes the JWT as an HttpOnly session cookie.
Types ¶
type CallbackOptions ¶ added in v0.3.0
type CallbackOptions struct {
// OnAuthenticated runs after a successful code exchange and before the
// session cookie is written -- the place to provision or update a local
// user from the claims. The returned defaultRedirect, when non-empty, is
// the post-login destination used if the flow carries no explicit
// redirect (e.g. a welcome page for new accounts). A returned error
// aborts the login: no session cookie is set and the response is a 500.
OnAuthenticated func(r *http.Request, accessToken string, claims *Claims) (defaultRedirect string, err error)
// SanitizeRedirect filters the redirect-cookie value before use; return
// "" to reject it. Apps should restrict the destination to local paths
// as defense in depth against a planted cookie.
SanitizeRedirect func(value string) string
// Finish completes the response after the session cookie is set,
// replacing the default 302 to redirectTo. For flows that must not
// navigate, such as a login popup that posts a message to its opener
// and closes.
Finish func(w http.ResponseWriter, r *http.Request, redirectTo string)
// Logf receives diagnostic messages for failed callbacks (token exchange
// and provisioning errors, upstream error params). Nil disables logging.
Logf func(format string, args ...any)
}
CallbackOptions customizes the app-specific parts of CallbackHandler. The zero value is a working configuration.
type Claims ¶
type Claims struct {
Sub string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name"`
Roles []string `json:"roles,omitempty"`
// Exp is the token's expiry as a Unix timestamp (the JWT "exp" claim).
// Callers can use it to renew proactively -- via Refresh, before a request
// fails -- rather than reacting to a validation failure. Zero if the token
// carried no exp.
Exp int64 `json:"exp,omitempty"`
}
Claims holds the JWT claims extracted from an ID or access token.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an OIDC relying party that performs authorization code flows with PKCE and validates JWTs using keys from the provider's JWKS endpoint.
Discovery, JWKS caching, and signature verification are handled by github.com/coreos/go-oidc/v3. The authorization code flow is handled by golang.org/x/oauth2.
func New ¶
New creates a Client by performing OIDC discovery against the configured IssuerURL. Returns an error if discovery fails or the configuration is incomplete. Use NewLazy when the application must boot even while the provider is unreachable.
func NewLazy ¶ added in v0.3.1
NewLazy creates a Client without contacting the provider. Discovery (and dynamic registration) run in a background goroutine, retrying with exponential backoff until they succeed or ctx is cancelled, so an unavailable IdP degrades sign-in instead of blocking application startup.
Until the first success, Ready reports false, token operations return ErrNotReady, AuthorizeURL returns "", and CallbackHandler responds 503. The error return covers static misconfiguration only.
ctx must outlive the Client: it bounds both the retry loop and the provider's later JWKS fetches.
func (*Client) AuthorizeURL ¶
AuthorizeURL builds the OIDC authorization URL with PKCE. verifier is the PKCE code verifier (store it for the callback); the S256 challenge is computed automatically. Returns "" while a lazy client is not ready (the endpoints are unknown before discovery) — check Client.Ready before starting a flow.
func (*Client) CallbackHandler ¶ added in v0.3.0
func (c *Client) CallbackHandler(opts CallbackOptions) http.Handler
CallbackHandler returns the redirect-URI endpoint for the authorization code flow: it surfaces upstream errors, validates the state nonce against the flow cookie, exchanges the code with PKCE, invokes OnAuthenticated, writes the session cookie, clears the flow cookies, and sends the user to the destination from the flow's redirect cookie (default "/").
func (*Client) ClientID ¶
ClientID returns the OIDC client ID in effect for this Client. When the provider supports RFC 7591 dynamic registration, this is the server-assigned id (which may differ from Config.ClientID); otherwise it is the pre-registered id from Config. On a not-yet-ready lazy client it is the Config value.
func (*Client) CookieName ¶
CookieName returns the configured session cookie name.
func (*Client) Exchange ¶ added in v0.4.0
Exchange exchanges an authorization code for tokens using the PKCE verifier. It returns the Tokens (access token, refresh token when offline access was granted, and access-token expiry) along with the verified claims from the ID token. Persist Tokens.RefreshToken to renew the session later via Client.Refresh; on a rotating IdP it must be stored, not the request-time token.
func (*Client) ExchangeCode
deprecated
func (c *Client) ExchangeCode(ctx context.Context, code, verifier string) (accessToken string, claims *Claims, err error)
ExchangeCode exchanges an authorization code for tokens using the PKCE verifier, returning the access token (for session storage) and the verified claims from the ID token.
Deprecated: use Client.Exchange, which additionally returns the refresh token needed to renew the session via Client.Refresh and the access-token expiry. ExchangeCode discards both.
func (*Client) FlowConfigured ¶
FlowConfigured reports whether the OIDC authorization code flow is configured (i.e., ClientID and CallbackURL are set).
func (*Client) LoginURL ¶
LoginURL returns a URL to redirect unauthenticated users to the IdP login.
func (*Client) LogoutURL ¶
LogoutURL returns the IdP logout URL. When the provider advertises an end_session_endpoint (OIDC RP-Initiated Logout), that discovered, fully qualified URL is returned -- it is issuer/tenant-scoped and actually exists. Only when no such endpoint is advertised (or discovery has not completed) does this fall back to the legacy WebauthURL/logout path, which historically was a fabricated guess and may 404 on providers that do not serve it.
func (*Client) Ready ¶ added in v0.3.1
Ready reports whether provider discovery has completed. A client from New is always ready; a client from NewLazy becomes ready when the background retry first succeeds. While false, token operations return ErrNotReady.
func (*Client) Refresh ¶ added in v0.4.0
Refresh renews a session using a refresh token obtained from Client.Exchange (which requires Config.OfflineAccess). It POSTs grant_type=refresh_token to the provider's token endpoint and returns the new Tokens and verified claims.
On an IdP that rotates refresh tokens -- as webauth does -- the returned Tokens.RefreshToken is a NEW token: persist it and discard the one passed in. The caller is responsible for storing the rotated token (oidclient keeps no session state); failing to do so ends the session on the next refresh.
Returns ErrNoRefreshToken for an empty token and ErrNotReady while a lazy client's discovery is pending.
func (*Client) RegisterURL ¶
RegisterURL builds the URL to the IdP's registration page with the OIDC parameters needed to complete an authorization code flow after signup. The verifier is the same PKCE code verifier used with ExchangeCode. After registration, the IdP redirects to CallbackURL with an authorization code, identical to the login flow.
func (*Client) Validate ¶
Validate parses and validates a raw access token JWT, returning the extracted claims. The token's signature is verified against the provider's JWKS, and standard claims (issuer, expiry) are checked. Returns ErrNotReady while a lazy client's discovery is pending — treat it as an unauthenticated request.
type Config ¶
type Config struct {
// IssuerURL is the OIDC issuer (e.g. "https://auth.example.com/t/mytenant").
// Used for discovery and token verification. Required.
IssuerURL string
// CookieName is the name of the HttpOnly cookie storing the JWT session token.
CookieName string
// ClientID is this application's pre-registered OIDC client ID. Used as-is
// when the provider does not advertise a registration_endpoint. When the
// provider supports RFC 7591 dynamic client registration, this field is
// ignored and the server-assigned client_id is used instead — query the
// runtime value via Client.ClientID after New returns.
ClientID string
// ClientName is optional client metadata (RFC 7591 §2) sent during dynamic
// registration. Servers may use it for display in admin UIs and consent
// screens. Ignored when the provider does not advertise a registration_endpoint.
ClientName string
// ClientSecret is the static secret for a confidential client (e.g. a Google
// "Web application" credential). Set it together with a pre-registered
// ClientID for providers that issue a secret and do not support RFC 7591
// dynamic registration; it is sent in the token-exchange request body
// alongside the PKCE verifier. Leave empty for public PKCE clients. When the
// provider advertises a registration_endpoint, dynamic registration runs and
// the server-assigned secret supersedes this value.
ClientSecret string
// CallbackURL is the registered redirect URI for the authorization code flow.
CallbackURL string
// OfflineAccess requests the "offline_access" scope so the IdP issues a
// refresh token, enabling session renewal via [Client.Refresh] without an
// interactive redirect. Leave false for short-lived sessions: a refresh
// token is a long-lived, high-value credential and a relying party that
// does not renew sessions should not request one. webauth gates refresh
// issuance on this scope; for Google, prefer a confidential client (offline
// issuance there keys off access_type, which this scope does not set).
OfflineAccess bool
// WebauthURL is the base URL of the auth server (e.g. "https://auth.example.com").
// Used for LoginURL/LogoutURL construction. Derived from IssuerURL if empty.
WebauthURL string
// HTTPClient overrides the default HTTP client for OIDC discovery, JWKS
// fetches, and token exchange requests.
HTTPClient *http.Client
// Logf receives diagnostic messages from [NewLazy]'s background discovery
// retries. Nil disables logging.
Logf func(format string, args ...any)
}
Config configures the OIDC client.
type Tokens ¶ added in v0.4.0
Tokens holds the credentials returned by a successful code exchange (Client.Exchange) or renewal (Client.Refresh).
RefreshToken is empty unless the IdP granted offline access (see Config.OfflineAccess). On an IdP that rotates refresh tokens -- as webauth does, with replay detection -- each Exchange/Refresh returns a *new* RefreshToken and the caller MUST persist it, discarding the one just used; reusing a rotated token trips replay detection and ends the session.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package session provides server-side OIDC sessions for relying parties built on oidclient: the browser holds an opaque session id in a cookie, while the access token and the rotating refresh token live server-side, encrypted at rest.
|
Package session provides server-side OIDC sessions for relying parties built on oidclient: the browser holds an opaque session id in a cookie, while the access token and the rotating refresh token live server-side, encrypted at rest. |