Documentation
¶
Overview ¶
Package oidc signs a user in with an OpenID Connect provider. Provider.Begin seals the flow's state, nonce, PKCE verifier and intent into a browser-bound cookie and returns the authorization URL; Provider.Finish opens that cookie on the callback, exchanges the code and verifies the ID token. Nothing is stored server-side. The flow cookie always takes the secure name and the Secure flag, because every OIDC route needs a secure request: over plain HTTP the browser drops it, so the flow fails closed. It imports the root access package and never the reverse.
Index ¶
- Constants
- Variables
- func UsernameCandidate(c Claims) (string, error)
- type BeginRequest
- type Callback
- type Claims
- type Config
- type Flow
- type Intent
- type Provider
- func (p *Provider) Begin(w http.ResponseWriter, r *http.Request, session access.CookieConfig, ...) (authURL string, err error)
- func (p *Provider) Finish(w http.ResponseWriter, r *http.Request, session access.CookieConfig, ...) (Flow, Claims, error)
- func (p *Provider) Issuer() string
- func (p *Provider) LogValue() slog.Value
- type ProviderError
- type UsernameError
Constants ¶
const MaxInviteHashBytes = 64
MaxInviteHashBytes is the longest BeginRequest.InviteHash Begin accepts: the hex SHA-256 account stores a one-time token under.
const MaxRedirectBytes = 512
MaxRedirectBytes is the longest BeginRequest.Redirect Begin accepts.
Variables ¶
var ( // ErrDiscovery reports a provider NewProvider could not reach: a // connection or TLS failure, a timeout, a redirect or an answer other // than 200. A retry can succeed. ErrDiscovery = errors.New("oidc: provider discovery failed") // ErrProviderInvalid reports a provider that answered with a discovery // document or JWK Set access will not use. Only the provider's own // configuration, or the issuer URL, can fix it, so an app shows it on // the issuer field rather than retrying soon. It never matches // ErrDiscovery. ErrProviderInvalid = errors.New("oidc: provider configuration refused") ErrExchange = errors.New("oidc: code exchange failed") ErrTokenInvalid = errors.New("oidc: ID token verification failed") ErrNonceMismatch = errors.New("oidc: nonce mismatch") ErrConfigInvalid = errors.New("oidc: invalid configuration") ErrNoUsername = errors.New("oidc: token has no preferred_username or verified email claim") // ErrFlowInvalid reports a flow cookie that is missing, forged, expired, // sealed by another provider or answered with another state, and a // malformed BeginRequest or a cross-site begin that Begin refuses. ErrFlowInvalid = errors.New("oidc: sign-in flow invalid") // ErrStaleAuthentication reports a flow of any intent but sign-in whose // ID token's auth_time is absent or more than 60 seconds before the flow // began. ErrStaleAuthentication = errors.New("oidc: the provider did not authenticate the user again") ErrRedirectTooLong = errors.New("oidc: redirect longer than MaxRedirectBytes") )
Sentinel errors for OIDC operations.
Functions ¶
func UsernameCandidate ¶
UsernameCandidate is preferred_username when present, else email when email_verified, normalised by access.NormalizeUsername. It returns ErrNoUsername when neither applies, and a *UsernameError naming the claim when the chosen one does not normalise; it never falls back from a refused preferred_username to the email.
Types ¶
type BeginRequest ¶
type BeginRequest struct {
Intent Intent
SessionID string
// Redirect is the app's relative return path, at most MaxRedirectBytes,
// passed through access.ValidateRedirectURI, so an unsafe one becomes "/".
Redirect string
// InviteHash, opaque to oidc and at most MaxInviteHashBytes, is required
// for IntentInvite and must be empty for the others. It is sealed in the
// flow cookie and never sent to the provider.
InviteHash []byte
UserID int64
}
BeginRequest names what the flow is for. SessionID, at most 64 bytes, and a positive UserID are required for IntentLink and IntentStepUp and must be empty for the other intents.
type Callback ¶
Callback is what the provider sent on its redirect to the callback (RFC 6749 sections 4.1.2 and 4.1.2.1), decoded once by the caller.
type Claims ¶
type Claims struct {
// AuthTime is the auth_time claim, zero when the token has none.
AuthTime time.Time
// Raw holds every verified claim, by name.
Raw map[string]json.RawMessage
Identity access.OIDCIdentity
Email string
PreferredUsername string
Name string
// EmailVerified is decoded from a JSON boolean or the strings "true"
// and "false", which some providers send.
EmailVerified bool
}
Claims are the claims of an ID token Finish verified.
type Config ¶
type Config struct {
// HTTPClient is the client for discovery, JWKS and token calls; nil
// means a default client. The provider uses a copy: a zero Timeout
// becomes 10s, and the transport is wrapped so a response body past 1
// MiB is refused, whatever length it declares. A negative Timeout is
// refused. Jar and the transport's dialer and TLS settings are kept as
// given; CheckRedirect applies to the token exchange only, since
// discovery and the key set follow no redirect.
HTTPClient *http.Client
// FlowSealer seals the flow cookie; nil means a new ephemeral sealer
// per Provider, so a flow begun under one Provider value cannot finish
// under a rebuilt one; an app that rebuilds providers passes one sealer
// that outlives them.
FlowSealer *access.Sealer
// Now is the clock for the flow cookie, the ID token's time claims, and
// the key set's age and refetch gate; nil means time.Now.
Now func() time.Time
// Logger receives the key set's WARNs; nil means slog.Default() at
// each call.
Logger *slog.Logger
ClientSecret access.Secret
IssuerURL string
ClientID string
RedirectURL string
// Scopes is the requested scope list, which must include "openid"; nil
// means openid, profile and email.
Scopes []string
}
Config is a Provider's settings. Every optional field's zero value is its default.
func (Config) Validate ¶
Validate requires an https issuer and redirect URL, except http on a loopback host, each absolute with a host and no userinfo or fragment, and the issuer with no query (OpenID Connect Discovery 1.0 section 3); a client ID; a Scopes list that includes "openid" when one is given; a non-negative HTTPClient.Timeout; and a largest flow that seals and fits its cookie. It makes no request. Every refusal matches ErrConfigInvalid, and NewProvider refuses no other config with it.
type Flow ¶
type Flow struct {
BeganAt time.Time
Intent Intent
SessionID string
Redirect string
InviteHash []byte
UserID int64
}
Flow is what Finish recovers from the flow cookie.
type Intent ¶
type Intent string
Intent is what a flow is for.
const ( IntentSignIn Intent = "signin" IntentLink Intent = "link" // started from a session; links on return IntentStepUp Intent = "stepup" // started from a session; re-proves on return IntentInvite Intent = "invite" // started from an invite; creates the invited account on return )
The four intents. Every intent but sign-in makes the provider authenticate the user again.
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider is an OpenID Connect provider discovered by NewProvider. It is immutable; an app swaps its pointer when settings change.
func NewProvider ¶
NewProvider refuses a cfg that fails Validate, then fetches discovery and the JWK Set through cfg's client, following no redirect; no error names a URL. It fails with ErrDiscovery when either could not be fetched or answered other than 200, and with ErrProviderInvalid when the provider answered with a body past 1 MiB, a document that is not one JSON object, names another issuer, has no accepted algorithm or, naming the field, an endpoint outside the https rule (http only under a loopback http issuer), or a JWK Set that is malformed or holds no usable key.
func (*Provider) Begin ¶
func (p *Provider) Begin(w http.ResponseWriter, r *http.Request, session access.CookieConfig, req BeginRequest) (authURL string, err error)
Begin seals the flow into the flow cookie, session.Derive("oidc", Lax) under its secure name, and returns the authorization URL, with max_age=0 and prompt=login for every intent but IntentSignIn. Before any Set-Cookie it refuses a Redirect over MaxRedirectBytes with ErrRedirectTooLong, first; with ErrConfigInvalid, a session config that fails Validate; with ErrFlowInvalid, an unknown intent or IDs or a hash that do not fit it, and any intent but sign-in whose Sec-Fetch-Site is present and not same-origin. NewProvider owns the flow cookie's size.
func (*Provider) Finish ¶
func (p *Provider) Finish(w http.ResponseWriter, r *http.Request, session access.CookieConfig, cb Callback) (Flow, Claims, error)
Finish reads and clears the flow cookie derived from session, under its secure name, on every outcome past session.Validate, checks cb.State, exchanges cb.Code and verifies the ID token. It reads the request only for the cookie and its context, never its URL. A session config that fails Validate is ErrConfigInvalid with no Set-Cookie. An error after the cookie opened, for this provider, comes with the opened Flow, so the caller can return the browser to the page the flow began on; before that, Flow is zero.
type ProviderError ¶
type ProviderError struct {
// Code is one of the codes of RFC 6749 section 4.1.2.1, or "other" for
// any other value. The provider's error_description is never read.
Code string
}
ProviderError is the provider's error answer to the authorization request, read only after the callback's state matched the flow's.
func (*ProviderError) Error ¶
func (e *ProviderError) Error() string
type UsernameError ¶
type UsernameError struct {
// Err is NormalizeUsername's error, matching access.ErrUsernameEmpty or
// access.ErrUsernameInvalid.
Err error
// Claim is "preferred_username" or "email".
Claim string
}
UsernameError reports that the claim UsernameCandidate chose is not a username access.NormalizeUsername accepts.
func (*UsernameError) Error ¶
func (e *UsernameError) Error() string
func (*UsernameError) Unwrap ¶
func (e *UsernameError) Unwrap() error
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
bodycap
Package bodycap caps every response body an http.Client reads at MaxBytes, whatever length the response declares.
|
Package bodycap caps every response body an http.Client reads at MaxBytes, whatever length the response declares. |
|
discovery
Package discovery fetches and checks an OpenID Connect provider's discovery document (OpenID Connect Discovery 1.0).
|
Package discovery fetches and checks an OpenID Connect provider's discovery document (OpenID Connect Discovery 1.0). |
|
jsonmember
Package jsonmember reads JSON documents member by member, by each member's JSON kind (RFC 8259).
|
Package jsonmember reads JSON documents member by member, by each member's JSON kind (RFC 8259). |
|
jwk
Package jwk parses a JWK Set (RFC 7517) into the public keys oidc verifies ID tokens with: RSA, EC on P-256, P-384 and P-521, and OKP Ed25519 (RFC 7518 §6, RFC 8037 §2).
|
Package jwk parses a JWK Set (RFC 7517) into the public keys oidc verifies ID tokens with: RSA, EC on P-256, P-384 and P-521, and OKP Ed25519 (RFC 7518 §6, RFC 8037 §2). |
|
jws
Package jws verifies a compact JWS (RFC 7515) carrying a signed JWT (RFC 7519) under the algorithms of package jwk, and returns its payload.
|
Package jws verifies a compact JWS (RFC 7515) carrying a signed JWT (RFC 7519) under the algorithms of package jwk, and returns its payload. |