auth

package
v0.0.19 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package auth tells a service who made a request from an OAuth2 access token Ory Hydra issued. Two ways, one result (Auth):

  • JWT access tokens (strategies.access_token: jwt): verified locally against Hydra's public keys, without a call. A revoked token stays valid until it expires (ttl.access_token): the model's promise.
  • Introspection: any access token, opaque or JWT, asked of Hydra's admin API on every call. Nothing is cached: a revoked token fails the next call, at the price of a call to the admin API.

Neither caches tokens, so every replica of a service answers alike. The only cache is of the public keys, fetched on first use, on an unknown kid and in the background when old.

Index

Constants

View Source
const (
	// FromJWT: verified locally from a JWT access token.
	FromJWT = "jwt"
	// FromIntrospection: Hydra answered for the token.
	FromIntrospection = "introspection"
)

Source of an Auth.

Variables

View Source
var (
	// ErrNoCredential: the request carries no bearer token.
	ErrNoCredential = errors.New("auth: no credential")
	// ErrInvalid: the token is malformed, badly signed, not an access token
	// or its claims fail.
	ErrInvalid = errors.New("auth: invalid token")
	// ErrExpired: the token's exp has passed (or its nbf has not come).
	ErrExpired = errors.New("auth: token expired")
	// ErrUnknownKey: the token is signed with a key Hydra does not publish.
	ErrUnknownKey = errors.New("auth: token signed with an unknown key")
	// ErrInactive: Hydra says the token is not active (revoked, expired or
	// never issued).
	ErrInactive = errors.New("auth: token not active")
	// ErrUnavailable: Hydra or its keys could not be reached.
	ErrUnavailable = errors.New("auth: unavailable")
)

Errors. Every error of the package wraps one of them.

View Source
var ErrOptions = errors.New("auth: options")

ErrOptions: an option is missing or wrong.

Functions

func GRPCCode

func GRPCCode(err error) codes.Code

GRPCCode is the code a refusal for err answers with.

func HTTPStatus

func HTTPStatus(err error) int

HTTPStatus is the status a refusal for err answers with.

func WithAuth

func WithAuth(ctx context.Context, a Auth) context.Context

WithAuth returns ctx carrying a.

Types

type Auth

type Auth struct {
	// Subject is the user the token was issued for, or the client itself
	// for client credentials.
	Subject string
	// ClientID is the OAuth2 client the token was issued to.
	ClientID string
	// Scopes granted to the token.
	Scopes []string
	// Audience the token is meant for.
	Audience []string
	// ExpiresAt and IssuedAt of the token.
	ExpiresAt time.Time
	IssuedAt  time.Time
	// TokenID is the token's jti (JWT) — empty from introspection.
	TokenID string
	// Extra are the claims the consent or the token hook added (Hydra's
	// "ext"); with mirrored top-level claims they are in Claims too.
	Extra map[string]any
	// Claims are all of a JWT's claims (FromJWT).
	Claims map[string]any
	// Source is FromJWT or FromIntrospection.
	Source string
}

Auth is who a token speaks for and what it may do.

func FromContext

func FromContext(ctx context.Context) (Auth, bool)

FromContext returns the Auth the middleware put into ctx.

func (Auth) HasScope

func (a Auth) HasScope(scope string) bool

HasScope reports whether the token was granted scope.

func (Auth) HasScopes

func (a Auth) HasScopes(scopes ...string) bool

HasScopes reports whether the token was granted every one of scopes.

func (Auth) Intended

func (a Auth) Intended(audience string) bool

Intended reports whether audience is among the token's.

func (Auth) IsClient

func (a Auth) IsClient() bool

IsClient reports whether the token speaks for its client alone (client credentials), not a user.

func (Auth) IsZero

func (a Auth) IsZero() bool

IsZero reports whether a is the zero Auth (nobody).

type Authenticator

type Authenticator struct {
	// Tokens verifies JWT access tokens locally; nil: JWTs go to
	// Introspection.
	Tokens *Tokens
	// Introspection asks Hydra; zero: opaque tokens are refused.
	Introspection Introspection
}

Authenticator finds a request's bearer token and verifies it: a JWT with Tokens, any other token (or a JWT when Tokens is nil) with Introspection. Either may be absent: that token is then refused.

func (Authenticator) Authenticate

func (a Authenticator) Authenticate(ctx context.Context, h http.Header) (Auth, error)

Authenticate verifies the bearer token the headers carry.

func (Authenticator) Optional

func (a Authenticator) Optional(next http.Handler) http.Handler

Optional lets requests without a token through without an Auth; a token that fails still gets 401.

func (Authenticator) Required

func (a Authenticator) Required(next http.Handler) http.Handler

Required lets through only requests a token authenticates; the others get 401 (503 when Hydra or its keys are unreachable).

func (Authenticator) StreamInterceptor

func (a Authenticator) StreamInterceptor(required bool) grpc.StreamServerInterceptor

StreamInterceptor authenticates every stream (required: refuses anonymous streams too).

func (Authenticator) UnaryInterceptor

func (a Authenticator) UnaryInterceptor(required bool) grpc.UnaryServerInterceptor

UnaryInterceptor authenticates every unary call (required: refuses anonymous calls too).

type ExpiredError added in v0.0.19

type ExpiredError struct {
	Auth Auth
	// contains filtered or unexported fields
}

ExpiredError is the refusal of an access token whose signature, issuer and audience verified but whose exp has passed (or nbf has not come). It wraps ErrExpired; Auth names whose token it was, so a caller can tell the client exactly why it is refused. The token is still refused: never authenticate with Auth.

func (*ExpiredError) Error added in v0.0.19

func (e *ExpiredError) Error() string

func (*ExpiredError) Unwrap added in v0.0.19

func (e *ExpiredError) Unwrap() error

type Introspection

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

Introspection asks Hydra's admin API about a token on every call: no cache, so a revoked token fails the next call on every replica.

func NewIntrospection

func NewIntrospection(adminURL string, headers map[string]string, client *http.Client) (Introspection, error)

NewIntrospection asks Hydra's admin API at adminURL (as this service reaches it); headers go with every request (a proxy's authorization); client nil: a client with a 10s timeout.

func (Introspection) Verify

func (i Introspection) Verify(ctx context.Context, token string, scopes ...string) (Auth, error)

Verify asks Hydra whether token is an active access token and returns what it grants; scopes, when given, must all be granted (Hydra checks).

func (Introspection) WithAudience added in v0.0.5

func (i Introspection) WithAudience(audience string) Introspection

WithAudience is i requiring tokens whose aud holds audience (see TokensOptions.Audience).

type Tokens

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

Tokens verifies JWT access tokens locally against Hydra's public keys. One Tokens serves every goroutine; it holds the keys' cache.

func NewTokens

func NewTokens(o TokensOptions) (*Tokens, error)

NewTokens creates the verifier; it fetches nothing until the first token.

func (*Tokens) Verify

func (t *Tokens) Verify(ctx context.Context, token string) (Auth, error)

Verify checks token's signature and claims and returns what it grants. An ID token, signed with Hydra's keys too, is refused: an access token carries client_id and scp, an ID token auth_time (and at_hash, nonce), which no consent can remove.

type TokensOptions

type TokensOptions struct {
	// Issuer is Hydra's issuer (urls.self.issuer) tokens must carry as iss.
	// Required.
	Issuer string
	// KeysURL is Hydra's public keys; empty: <Issuer>/.well-known/jwks.json.
	KeysURL string
	// Audience is a value tokens' aud must hold. Empty: not checked — then
	// a token Hydra issued for another API of the installation is accepted
	// too (its signature and issuer still are checked); set it when one
	// Hydra serves several APIs and have clients request the audience.
	Audience string
	// Leeway is the clock skew tolerated on exp, nbf and iat. Default 30s.
	Leeway time.Duration
	// HTTPClient fetches the keys. Default: a client with a 10s timeout.
	HTTPClient *http.Client
	// KeysMaxAge is how old the keys may get before a background refetch.
	// Default 10m. A token with an unknown kid fetches at once anyway.
	KeysMaxAge time.Duration
	// KeysMinRefresh is the least time between two fetches. Default 30s.
	KeysMinRefresh time.Duration
	// Now is the clock (tests). Default time.Now.
	Now func() time.Time
}

TokensOptions configure NewTokens.

Jump to

Keyboard shortcuts

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