oidc

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 20 Imported by: ? 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.

Documentation

Overview

Package oidc authenticates with an OpenID Connect provider: services getting access tokens for other services' APIs, services checking the access tokens they're sent, and people logging in to a service's web pages.

Index

Constants

View Source
const (
	// CallbackPath is where the provider sends the browser back to. Register
	// the service's URL with this path appended as the client's callback URL.
	CallbackPath = "/auth/callback"
)

Variables

View Source
var ErrBearerUnavailable = errors.New("token verification is unavailable")

ErrBearerUnavailable is wrapped by errors from Verify when the provider could not be discovered or its signing keys could not be fetched, so the token was not fully checked.

Functions

func BearerToken

func BearerToken(r *http.Request) (string, bool)

BearerToken returns the token from r's Authorization header, and whether there was a non-empty one using the Bearer scheme.

Types

type AccessToken

type AccessToken struct {
	Subject string
	Expiry  time.Time
	// contains filtered or unexported fields
}

AccessToken is a verified access token.

func (*AccessToken) Claims

func (t *AccessToken) Claims(v any) error

Claims decodes the token's claims into v.

type BearerConfig

type BearerConfig struct {
	// Issuer is the OpenID Connect issuer URL the tokens must come from.
	Issuer string
	// Audience is the audience tokens must name, normally the service's URL.
	// Exactly one of Audience and AudienceFunc must be set.
	Audience string
	// AudienceFunc gives the audience on first use, for services that only
	// know their URL once they are serving. It is called again after a
	// failure.
	AudienceFunc func(context.Context) (string, error)
	// WithSubject, if set, is given the request context and the token's
	// subject by Require, and returns the context the wrapped handler sees.
	WithSubject func(ctx context.Context, subject string) context.Context
	// Now is the clock tokens are checked against. It defaults to time.Now.
	Now func() time.Time
}

type BearerVerifier

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

BearerVerifier checks RFC 9068 access tokens sent as "Authorization: Bearer <token>".

The provider is discovered on first use rather than at construction, so a service still starts while its provider is down, and a failed discovery is tried again on the next request. Signing keys are cached, and fetched again when a token is signed with a key not yet seen, so tokens are otherwise checked without contacting the provider.

func NewBearerVerifier

func NewBearerVerifier(cfg BearerConfig) (*BearerVerifier, error)

NewBearerVerifier checks cfg and returns a BearerVerifier for it. The provider is not contacted until the first token is verified.

func (*BearerVerifier) Require

func (v *BearerVerifier) Require(next http.Handler) http.Handler

Require passes requests to next only with a valid token. A request without one gets a 401 with a WWW-Authenticate challenge, never a redirect. If the provider can't be reached it gets a 502 instead, since that isn't the caller's fault and a 401 might send it off to fetch a new token.

func (*BearerVerifier) Verify

func (v *BearerVerifier) Verify(ctx context.Context, raw string) (*AccessToken, error)

Verify checks raw is an access token from the issuer for the audience. The error wraps ErrBearerUnavailable if the provider could not be discovered or its signing keys could not be fetched.

A token is accepted if it is a JWT of type at+jwt, signed by one of the issuer's keys, issued by the issuer, unexpired, and with the configured audience (normally the service's own URL) among its audiences. There are no scopes: any such token is accepted. The type check is what stops an ID token, which is signed by the same keys, standing in for an access token.

type BrowserLogin

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

BrowserLogin puts a service's web pages behind an OpenID Connect login, using the authorization-code flow with PKCE. It requires a session, or a token where configured, on everything but the exempt paths.

There is no session store. A session is a cookie signed with the session key, so it survives restarts and deploys as long as the key stays the same, and it lasts as long as the configured Expiry says, whatever the ID token's own expiry. While a login is in progress, what the callback needs is kept in a cookie named after the login's state, so several tabs sent to log in at once (a browser restoring its tabs after the session ran out, say) each find their own.

Optionally, some or all paths also take RFC 9068 access tokens sent as "Authorization: Bearer <token>", with the service's URL as their audience, for other services calling an API; see BearerVerifier.

Requests let through with a session are also protected against cross-origin requests by http.CrossOriginProtection, so another site can't make changes using the browser's session cookie.

func NewBrowserLogin

func NewBrowserLogin(cfg BrowserLoginConfig) (*BrowserLogin, error)

NewBrowserLogin checks cfg and returns a BrowserLogin for it. The provider is not contacted until the first request that needs it, so a service still starts while its provider is down, and a failed discovery is tried again on the next request.

Exempt paths and the bearer prefix must be absolute and already clean, as path.Clean leaves them, not the root, and need no percent-encoding. A request for any other spelling of a path, such as "/static/../admin" or "/x/%2E%2E%2Fmetrics", is never exempt and never counted as under the bearer prefix.

func (*BrowserLogin) Wrap

func (l *BrowserLogin) Wrap(next http.Handler) http.Handler

Wrap serves CallbackPath itself, and passes other requests to next once they are logged in, exempt, or carry a valid token where one is accepted.

A browser loading a page without a session is sent off to log in, and brought back to the same page afterwards. Anything else without a session, such as a POST or a script's fetch, gets a 401 instead: a redirect would bring a POST back as a GET without its body, and a script can't follow one to the provider.

type BrowserLoginConfig

type BrowserLoginConfig struct {
	// Issuer is the OpenID Connect issuer URL.
	Issuer       string
	ClientID     string
	ClientSecret string
	// SessionKey signs the cookies, and must be at least
	// xhttp.MinCookieKeyLength bytes. Changing it logs everyone out.
	SessionKey string

	// BaseURL is the service's own URL: the base of the callback URL, and the
	// audience bearer tokens must name. It can't have a path, query or
	// fragment, since the service must be served from the root of its host.
	// Cookies are marked Secure only if it is https. Exactly one of BaseURL
	// and BaseURLFunc must be set.
	BaseURL string
	// BaseURLFunc gives the base URL on first use, for services that only know
	// their URL once they are serving. It is called again after a failure.
	BaseURLFunc func(context.Context) (string, error)

	// Expiry gives when a session started at the given time ends. It defaults
	// to the next 05:00 Europe/London, so a session runs out overnight rather
	// than while a form is half filled in.
	Expiry SessionExpiry

	// ExemptPrefixes are paths that need neither a login nor a token, along
	// with everything under them: "/static" opens "/static" and
	// "/static/app.css", but not "/staticfoo".
	ExemptPrefixes []string
	// ExemptPaths are matched exactly: "/metrics" opens that path and nothing
	// under it.
	ExemptPaths []string

	// BearerPrefix, if set, is a path that, with everything under it, takes
	// only bearer tokens and not sessions, such as "/api". A request there
	// without a valid token gets a 401 and never a redirect.
	BearerPrefix string
	// BearerAnywhere accepts a bearer token in place of a session on any path:
	// a request with a Bearer Authorization header is judged on the token
	// alone.
	BearerAnywhere bool

	// WithSubject, if set, is given the request context and the subject of
	// the session or bearer token, and returns the context the wrapped handler
	// sees.
	WithSubject func(ctx context.Context, subject string) context.Context
}

type ClientCredentials

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

ClientCredentials gets OAuth 2.0 access tokens with the client credentials grant, from one provider as one OAuth client, for any number of APIs identified by an RFC 8707 resource parameter. It is safe for concurrent use.

The provider's token endpoint is discovered when the first token is needed, not at construction, so a service whose provider is down still starts; a failed discovery is tried again on the next request. Each resource's token is cached until shortly before it expires, and then fetched again.

func NewClientCredentials

func NewClientCredentials(
	issuer, clientID, clientSecret string,
	opts ...ClientCredentialsOption,
) (*ClientCredentials, error)

NewClientCredentials returns a ClientCredentials for the provider at issuer. It makes no requests, so only fails if the configuration is unusable.

func (*ClientCredentials) Token

func (c *ClientCredentials) Token(ctx context.Context, resource string) (*oauth2.Token, error)

Token returns a current access token for resource, fetching a new one if the cached one has expired. An empty resource sends no resource parameter.

func (*ClientCredentials) TokenFunc

func (c *ClientCredentials) TokenFunc(resource string) func(ctx context.Context) (string, error)

TokenFunc returns a function giving the current access token for resource, suitable for Temporal's client.NewAPIKeyDynamicCredentials.

func (*ClientCredentials) TokenSource

func (c *ClientCredentials) TokenSource(resource string) oauth2.TokenSource

TokenSource returns a token source for resource. Its requests run without a context, so are bounded only by the HTTP client's timeout.

func (*ClientCredentials) Transport

func (c *ClientCredentials) Transport(resource string, base http.RoundTripper) http.RoundTripper

Transport returns a round tripper that sends each request through base with a bearer token for resource. A nil base means http.DefaultTransport. Token requests run under the outgoing request's context.

type ClientCredentialsOption

type ClientCredentialsOption func(*ClientCredentials)

ClientCredentialsOption configures a ClientCredentials.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientCredentialsOption

WithHTTPClient sets the client used for discovery and token requests. It should have a timeout, as a token request blocks every other request for the same resource. The default client times out after 30 seconds.

func WithHeaderAuth

func WithHeaderAuth() ClientCredentialsOption

WithHeaderAuth sends the client ID and secret in the Authorization header, rather than detecting which style the provider accepts. Detection answers a refusal by retrying with the credentials in the body, and reports that attempt's error instead of the original one.

func WithTrimmedResources

func WithTrimmedResources() ClientCredentialsOption

WithTrimmedResources removes trailing slashes from resources before sending them, for providers such as Pocket ID that strip them from the identifiers of registered APIs.

type SessionExpiry

type SessionExpiry func(loggedIn time.Time) time.Time

SessionExpiry gives the time a session started at loggedIn ends, which must be after loggedIn.

func ExpireAfter

func ExpireAfter(d time.Duration) SessionExpiry

ExpireAfter ends sessions a fixed duration after login.

func ExpireDailyAt

func ExpireDailyAt(hour int, loc *time.Location) SessionExpiry

ExpireDailyAt ends sessions at the first hour:00 in loc strictly after login. It is still hour:00 on the days the clocks change, unless that hour is skipped or repeated.

Jump to

Keyboard shortcuts

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