oidclient

package module
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: Apache-2.0 Imports: 17 Imported by: 3 modules, 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.

README

oidclient

CI Go Reference Go Report Card License

Experimental — internal use. This library is developed for infodancer projects that authenticate against infodancer/webauth. The API is unstable and may change without notice. If you're looking for a general-purpose OIDC relying party library for Go, consider coreos/go-oidc.

A thin convenience wrapper around coreos/go-oidc and golang.org/x/oauth2 that bundles OIDC discovery, JWKS-based JWT validation, the authorization code flow with PKCE, and cookie management into a single Client type. No custom cryptography — all signing and verification is delegated to go-oidc and go-jose.

Features

  • OIDC autodiscovery via go-oidc Provider
  • JWKS caching and key rotation handled by go-oidc
  • RS256 JWT validation with issuer and expiry enforcement
  • PKCE (S256) via x/oauth2
  • Authorization code flow — authorize URL, token exchange, ID token verification
  • Session renewal — offline_access opt-in, refresh-token grant with rotation handling, and proactive expiry via Claims.ExpiresAt
  • RFC 7591 dynamic client registration — automatic at startup when the provider advertises it
  • Static confidential clients — set ClientID + ClientSecret for providers that issue a secret and don't support RFC 7591 (e.g. Google)
  • Cookie helpers — secure defaults for OAuth flow state and JWT session cookies

Install

go get github.com/infodancer/oidclient

Usage

Creating a client
client, err := oidclient.New(ctx, oidclient.Config{
    IssuerURL:   "https://auth.example.com/t/mytenant",
    CookieName:  "myapp_jwt",
    ClientID:    "myapp",       // pre-registered fallback; ignored if the provider supports RFC 7591
    ClientName:  "My App",      // sent during dynamic registration (optional)
    CallbackURL: "https://myapp.example.com/auth/callback",
})

New contacts the provider synchronously and fails if it is unreachable. A web application that must boot even while its IdP is down should use NewLazy instead: it returns immediately, runs discovery in the background with exponential backoff, and degrades gracefully until the provider is reached -- Ready() reports false, token operations (Validate, Exchange, Refresh) return ErrNotReady (treat as anonymous), AuthorizeURL returns "" (check Ready() before starting a login flow), and CallbackHandler responds 503. An IdP outage then costs sign-in, not the whole site. The context passed to NewLazy must outlive the client; set Config.Logf to see retry diagnostics.

Dynamic client registration (RFC 7591)

If the provider's discovery document advertises registration_endpoint, New performs RFC 7591 dynamic client registration during startup, posts client metadata (client_name, redirect_uris), and uses the server-assigned client_id (and client_secret, if returned) for all subsequent operations. The runtime id is available via client.ClientID() for persistence across restarts:

log.Printf("registered as client_id=%s", client.ClientID())

When the provider does not advertise registration_endpoint, Config.ClientID is used as-is — the manual-provisioning case (the OIDC client was registered out-of-band at the provider's admin console). For a confidential client that also issues a secret (e.g. a Google "Web application" credential), set Config.ClientSecret alongside ClientID; it is sent in the token-exchange request body together with the PKCE verifier. Leave it empty for public PKCE clients. If the provider does advertise registration_endpoint, dynamic registration runs and the server-assigned secret supersedes ClientSecret.

Starting the login flow
func handleLogin(w http.ResponseWriter, r *http.Request) {
    verifier := oidclient.GenerateVerifier()
    state, _ := oidclient.GenerateNonce()
    secure := oidclient.IsSecure(r)

    oidclient.SetFlowCookie(w, oidclient.CookieVerifier, verifier, secure)
    oidclient.SetFlowCookie(w, oidclient.CookieState, state, secure)
    oidclient.SetFlowCookie(w, oidclient.CookieRedirect, r.URL.RequestURI(), secure)

    http.Redirect(w, r, client.AuthorizeURL(state, verifier), http.StatusFound)
}
Handling the callback
func handleCallback(w http.ResponseWriter, r *http.Request) {
    state := r.URL.Query().Get("state")
    if state != oidclient.FlowCookieValue(r, oidclient.CookieState) {
        http.Error(w, "invalid state", http.StatusBadRequest)
        return
    }

    verifier := oidclient.FlowCookieValue(r, oidclient.CookieVerifier)
    tokens, claims, err := client.Exchange(r.Context(), r.URL.Query().Get("code"), verifier)
    if err != nil {
        http.Error(w, "auth failed", http.StatusBadGateway)
        return
    }

    // claims.Sub, claims.Email, claims.Name, claims.Roles are available
    // for user provisioning here. When OfflineAccess is set, persist
    // tokens.RefreshToken to a server-side session store to renew later.

    secure := oidclient.IsSecure(r)
    oidclient.SetSessionCookie(w, client.CookieName(), tokens.AccessToken, secure)
    oidclient.ClearFlowCookies(w)

    redirectTo := oidclient.FlowCookieValue(r, oidclient.CookieRedirect)
    if redirectTo == "" {
        redirectTo = "/"
    }
    http.Redirect(w, r, redirectTo, http.StatusFound)
}
Validating requests
func requireAuth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        claims, err := client.ValidateCookie(r)
        if err != nil {
            // redirect to login...
            return
        }
        // claims.Sub, claims.Email, claims.Name, claims.Roles available
        next.ServeHTTP(w, r)
    })
}
Renewing a session

Set OfflineAccess: true on the Config so the IdP issues a refresh token, then persist tokens.RefreshToken from Exchange (a long-lived, high-value credential — keep it server-side, not in a browser cookie). When the access token nears expiry, renew without an interactive redirect:

newTokens, claims, err := client.Refresh(ctx, storedRefreshToken)
if err != nil {
    // ErrNoRefreshToken / a refused grant means the session cannot be
    // renewed silently — fall back to a full login.
    return
}
// The IdP may rotate the refresh token: store newTokens.RefreshToken and
// discard the one just used, or the next Refresh fails replay detection.
save(claims.Sub, newTokens.RefreshToken)
oidclient.SetSessionCookie(w, client.CookieName(), newTokens.AccessToken, secure)

Renew proactively rather than waiting for a 401: Claims.ExpiresAt() exposes the access-token expiry, so a caller can refresh a minute ahead of time.

Managed sessions

The oidclient/session subpackage wraps the renewal primitives above into a full server-side session lifecycle so relying parties don't hand-roll it: the browser holds an opaque session id, the access and rotating refresh tokens live server-side (encrypted at rest), and the manager validates and renews on each request -- collapsing concurrent renewals and guarding the refresh-token replay race. It persists nothing itself; the host supplies a session.Store over its own database and a session.Keyring for the at-rest encryption.

mgr, err := session.New(session.Config{
    Store:      myStore,   // implemented over the host DB
    Renewer:    client,    // the *oidclient.Client
    Keyring:    keyring,   // AES-256-GCM keys from the host's secret store
    CookieName: client.CookieName(),
})
// callback:       mgr.Start(w, r, tokens, claims)
// every request:  claims, err := mgr.Authenticate(r)  // renews transparently
// logout:         mgr.Destroy(w, r)

Design and rationale: docs/session-design.md.

Provisioning local users

The oidclient/rpuser subpackage is the audited claims -> local-user path, so relying parties don't each re-implement the post-login sync policy: users are keyed strictly on (issuer, subject) and never matched by email, mutable claims (email, email_verified) sync at login only, and the per-request path is read-only. The host keeps its schema and SQL, implementing rpuser.UserStore over its own users table; the package owns the flow.

store := myUserStore{}  // implements rpuser.UserStore over the host DB
prov := &rpuser.Provisioner{Store: store, Issuer: cfg.IssuerURL}
mw := &rpuser.Middleware{Authenticator: mgr, Store: store, Issuer: cfg.IssuerURL}

// callback, after Exchange:  u, isNew, err := prov.Provision(ctx, claims)
// route setup:               handler = mw.Optional(mux)
// in handlers:               rpuser.UserFromContext(ctx), rpuser.IdentityFromContext(ctx)

rpuser.Identity mirrors authz.Identity and carries no roles: authorization is resolved by the host's grant store (see infodancer/authz), never from claims. Rationale: issue #10.

License

Apache-2.0 — see LICENSE. Vulnerability reporting in SECURITY.md.

Documentation

Overview

Package oidclient is a client library for services consuming an OpenID Connect provider (designed for use with infodancer/webauth but compatible with any spec-compliant IdP). It supports the two ways a service consumes one:

  • As a relying party: Client runs the authorization code flow with PKCE, manages the session cookie, and validates its own tokens. This is what a website uses to sign users in.
  • As a resource server: ResourceServer validates access tokens it did not obtain, checking that each was issued for this resource. This is what an API uses to authenticate a caller who arrives holding a bearer token.

The distinction matters beyond naming -- a resource server must verify the audience and must never register itself as a client, and the relying party does the opposite of both. See the commentary on ResourceServer.

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

View Source
const (
	// Default cookie names for the OIDC authorization flow.
	CookieVerifier = "oauth_verifier"
	CookieState    = "oauth_state"
	CookieRedirect = "oauth_redirect"
)

Variables

View Source
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.

View Source
var (
	// ErrInvalidToken means the token does not authenticate: bad signature,
	// wrong issuer, wrong or missing audience, expired, malformed. Callers
	// answer 401.
	ErrInvalidToken = errors.New("oidclient: invalid token")

	// ErrKeysUnavailable means the token could not be checked because the
	// authorization server's key set could not be loaded. Callers answer 500,
	// never 401: telling a client its token is bad when the truth is that the
	// issuer is down sends it into a reauthentication loop against a server
	// that is already struggling.
	ErrKeysUnavailable = errors.New("oidclient: key set unavailable")
)

Sentinel errors returned by ResourceServer.Verify.

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

func FlowCookieValue(r *http.Request, name string) string

FlowCookieValue reads a named cookie value, returning "" if absent.

func GenerateNonce

func GenerateNonce() (string, error)

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 IsSecure

func IsSecure(r *http.Request) bool

IsSecure returns true if the request arrived over TLS or via an HTTPS proxy.

func LocalPath added in v0.8.0

func LocalPath(p string) string

LocalPath returns p when p is a relative same-origin path safe to hand to http.Redirect after the OIDC flow, or "" otherwise. It rejects:

  • absolute URLs (http://evil/, https://evil/),
  • protocol-relative URLs (//evil/path),
  • backslash-prefixed variants (/\evil/path) that some browsers historically normalised into a network-path reference,
  • anything parsing into a URL with a non-empty Scheme or Host.

Use it both where a redirect destination is first accepted (e.g. a login handler's "return" query parameter) and where it is read back (a CallbackOptions.SanitizeRedirect implementation, or the equivalent point in a hand-rolled callback handler) -- validating only one side leaves an opening for a redirect cookie planted out of band, e.g. from a compromised sibling subdomain.

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 AccessToken added in v0.9.0

type AccessToken struct {
	// Subject is the provider's stable identifier for the user (the sub
	// claim). It is the key to provision and look up local users by -- never
	// the email address, which can change and at some providers can be
	// released and re-registered by a different person.
	Subject string

	// Email and Name are display attributes. Never lookup keys.
	Email string
	Name  string

	// EmailVerified is the provider's assertion that the subject controls
	// Email. Carried so a provisioning policy can record it; it is never a
	// reason to match an account by email.
	EmailVerified bool

	// Scopes is the scope claim, already split on whitespace. What a scope
	// permits is the caller's decision; this reports only what was granted.
	Scopes []string

	// Roles is webauth's roles claim, carried through for callers that use it.
	Roles []string

	// Expiry is the validated expiration.
	Expiry time.Time
}

AccessToken is what a verified access token asserts, reduced to the parts a resource server acts on.

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.

func (*Claims) ExpiresAt added in v0.4.0

func (c *Claims) ExpiresAt() time.Time

ExpiresAt returns the token expiry as a time.Time, or the zero time if the token carried no exp claim.

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

func New(ctx context.Context, cfg Config) (*Client, error)

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

func NewLazy(ctx context.Context, cfg Config) (*Client, error)

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

func (c *Client) AuthorizeURL(state, verifier string) string

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

func (c *Client) ClientID() string

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

func (c *Client) CookieName() string

CookieName returns the configured session cookie name.

func (*Client) Exchange added in v0.4.0

func (c *Client) Exchange(ctx context.Context, code, verifier string) (*Tokens, *Claims, error)

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

func (c *Client) FlowConfigured() bool

FlowConfigured reports whether the OIDC authorization code flow is configured (i.e., ClientID and CallbackURL are set).

func (*Client) LoginURL

func (c *Client) LoginURL(redirectPath string) string

LoginURL returns a URL to redirect unauthenticated users to the IdP login.

func (*Client) LogoutURL

func (c *Client) LogoutURL() string

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

func (c *Client) Ready() bool

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

func (c *Client) Refresh(ctx context.Context, refreshToken string) (*Tokens, *Claims, error)

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

func (c *Client) RegisterURL(state, verifier string) string

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

func (c *Client) Validate(ctx context.Context, tokenStr string) (*Claims, error)

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.

func (*Client) ValidateCookie

func (c *Client) ValidateCookie(r *http.Request) (*Claims, error)

ValidateCookie extracts the JWT from the session cookie and validates it. Returns ErrNoCookie if the cookie is absent.

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 ResourceServer added in v0.9.0

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

ResourceServer validates access tokens issued by one provider for one resource. It is safe for concurrent use.

func NewResourceServer added in v0.9.0

func NewResourceServer(ctx context.Context, cfg ResourceServerConfig) (*ResourceServer, error)

NewResourceServer returns a ResourceServer for cfg.

When cfg.JWKSURL is set, no network request is made here. When it is empty, OIDC discovery runs against cfg.IssuerURL and an unreachable provider is a construction error.

func (*ResourceServer) Verify added in v0.9.0

func (rs *ResourceServer) Verify(ctx context.Context, token string) (*AccessToken, error)

Verify checks token and returns what it asserts.

An error matching ErrInvalidToken means the token does not authenticate. An error matching ErrKeysUnavailable means the check could not be performed. Callers must map those to 401 and 500 respectively.

type ResourceServerConfig added in v0.9.0

type ResourceServerConfig struct {
	// IssuerURL is the provider's issuer identifier, compared exactly against
	// the iss claim. Required.
	IssuerURL string

	// Resource is this resource server's own identifier -- for an MCP server,
	// its endpoint URL. A token must name it in aud. Required.
	Resource string

	// JWKSURL is where the provider publishes its signing keys. Optional: when
	// empty it is discovered from IssuerURL, which makes construction depend on
	// the provider being reachable. Setting it explicitly means construction
	// touches the network not at all, so a daemon starts even when its
	// authorization server is down and only token verification is affected.
	JWKSURL string

	// HTTPClient fetches discovery and key-set documents. Defaults to a client
	// with a short timeout: a key fetch happens on the request path.
	HTTPClient *http.Client

	// MinKeyRefresh is the floor between key-set refetches triggered by an
	// unrecognised key id. Defaults to defaultMinKeyRefresh.
	MinKeyRefresh time.Duration
}

ResourceServerConfig configures a ResourceServer.

type Tokens added in v0.4.0

type Tokens struct {
	AccessToken  string
	RefreshToken string
	Expiry       time.Time
}

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 rpuser is the audited claims -> local-user path for relying parties built on oidclient: it turns the verified claims of a completed login into a provisioned row in the host's own users table, and resolves that row again on each request.
Package rpuser is the audited claims -> local-user path for relying parties built on oidclient: it turns the verified claims of a completed login into a provisioned row in the host's own users table, and resolves that row again on each request.
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.

Jump to

Keyboard shortcuts

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