auth

package
v0.0.52 Latest Latest
Warning

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

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

Documentation

Overview

Package auth tells a service who made a request, from the credentials Ory Kratos gives a signed-in user. Two ways, one result (Auth):

  • Tokens: a short JWT the user's client gets from /sessions/whoami?tokenize_as=backplane (backplane-kratos configures the template and serves its public keys). Verified locally, without a call: a revoked session stops getting tokens at once, a token already issued stays valid until it expires (the settings' TTL).
  • Sessions: the session cookie or session token itself, asked of Kratos's /sessions/whoami on every call. Nothing is cached: a revoked session fails the next call, at the price of a call.

Neither caches users: tokens need no cache, sessions have none, 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 (
	// FromToken: verified from a token, locally.
	FromToken = "token"
	// FromSession: Kratos answered for the session.
	FromSession = "session"
)

Source of an Auth.

View Source
const (
	AAL1 = "aal1"
	AAL2 = "aal2"
	AAL3 = "aal3"
)

Assurance levels, weakest first.

View Source
const DefaultCookie = "ory_kratos_session"

DefaultCookie is Kratos's session cookie name.

Variables

View Source
var (
	// ErrNoCredential: the request carries no token, cookie or session token.
	ErrNoCredential = errors.New("auth: no credential")
	// ErrInvalid: the token is malformed, badly signed 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 the issuer does not
	// publish.
	ErrUnknownKey = errors.New("auth: token signed with an unknown key")
	// ErrUnauthenticated: Kratos knows no active session for the credential.
	ErrUnauthenticated = errors.New("auth: no active session")
	// ErrSecondFactor: the session has to complete a second factor first
	// (whoami's required_aal is highest_available).
	ErrSecondFactor = errors.New("auth: the session needs its second factor")
	// ErrUnavailable: Kratos or the 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 Address

type Address struct {
	Value    string `json:"value"`
	Via      string `json:"via"`
	Verified bool   `json:"verified"`
}

Address is a verifiable address of the identity.

type Auth

type Auth struct {
	// IdentityID is the Kratos identity (a token's sub).
	IdentityID string
	// SessionID is the Kratos session (a token's sid).
	SessionID string
	// AAL is the session's assurance level: aal1 one factor, aal2 two.
	AAL string
	// Methods are how the session authenticated (password, code, totp,
	// webauthn, passkey, oidc, lookup_secret...), in order.
	Methods []string
	// AuthenticatedAt is when the user last proved who they are.
	AuthenticatedAt time.Time
	// ExpiresAt is when the token or the session expires.
	ExpiresAt time.Time
	// Email is the identity's email trait, when it has one.
	Email string
	// SchemaID is the identity's schema.
	SchemaID string
	// Metadata is the identity's public metadata (roles live there).
	Metadata map[string]any
	// Source is FromToken or FromSession.
	Source string
	// Claims are all of a token's claims (FromToken).
	Claims map[string]any
	// Session is the whole session Kratos returned (FromSession).
	Session *Session
}

Auth is who made a request and how they signed in.

func FromContext

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

FromContext returns the Auth the middleware put into ctx.

func (Auth) AtLeast

func (a Auth) AtLeast(aal string) bool

AtLeast reports whether the session's assurance level is aal or higher.

func (Auth) AuthenticatedWithin

func (a Auth) AuthenticatedWithin(d time.Duration, now time.Time) bool

AuthenticatedWithin reports whether the user proved who they are within d before now: a sensitive action asks for a fresh sign-in.

func (Auth) HasRole

func (a Auth) HasRole(role string) bool

HasRole reports whether the public metadata's roles hold role.

func (Auth) IsZero

func (a Auth) IsZero() bool

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

func (Auth) Roles

func (a Auth) Roles() []string

Roles are the strings of the public metadata's "roles" list.

func (Auth) UsedMethod

func (a Auth) UsedMethod(method string) bool

UsedMethod reports whether the session authenticated with method.

type Authenticator

type Authenticator struct {
	// Tokens verifies bearer JWTs; nil: refused.
	Tokens *Tokens
	// Sessions asks Kratos about session tokens and cookies; zero: refused.
	Sessions Sessions
	// CookieName is Kratos's session cookie; empty: ory_kratos_session.
	CookieName string
}

Authenticator finds a request's credential and verifies it: a bearer JWT with Tokens, a session token or Kratos's cookie with Sessions. Either may be absent: that credential is then refused.

func (Authenticator) Authenticate

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

Authenticate verifies the credential the headers carry. A JWT bearer goes to Tokens; a non-JWT bearer, X-Session-Token or the session cookie to Sessions.

func (Authenticator) Optional

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

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

func (Authenticator) Required

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

Required lets through only requests a credential authenticates; the others get 401 (403 when the second factor is pending, 503 when the keys or Kratos 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 Credential

type Credential struct {
	// Cookie is the request's whole Cookie header: Kratos picks its own.
	Cookie string
	// Token is a session token (ory_st_...).
	Token string
}

Credential is what proves a session: the browser's cookies or a native app's session token.

func (Credential) IsZero

func (c Credential) IsZero() bool

IsZero reports whether c holds nothing.

type Device

type Device struct {
	ID        string `json:"id"`
	IPAddress string `json:"ip_address"`
	UserAgent string `json:"user_agent"`
	Location  string `json:"location"`
}

Device is a device the session was used from.

type ExpiredError added in v0.0.36

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

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

func (*ExpiredError) Error added in v0.0.36

func (e *ExpiredError) Error() string

func (*ExpiredError) Unwrap added in v0.0.36

func (e *ExpiredError) Unwrap() error

type Identity

type Identity struct {
	ID                  string          `json:"id"`
	SchemaID            string          `json:"schema_id"`
	State               string          `json:"state"`
	Traits              json.RawMessage `json:"traits"`
	MetadataPublic      map[string]any  `json:"metadata_public"`
	VerifiableAddresses []Address       `json:"verifiable_addresses"`
	ExternalID          string          `json:"external_id,omitempty"`
}

Identity is the session's identity.

type Session

type Session struct {
	ID              string          `json:"id"`
	Active          bool            `json:"active"`
	ExpiresAt       time.Time       `json:"expires_at"`
	AuthenticatedAt time.Time       `json:"authenticated_at"`
	IssuedAt        time.Time       `json:"issued_at"`
	AAL             string          `json:"authenticator_assurance_level"`
	Methods         []SessionMethod `json:"authentication_methods"`
	Identity        Identity        `json:"identity"`
	Devices         []Device        `json:"devices"`
	// Tokenized is the session's token when asked for (Tokenize).
	Tokenized string `json:"tokenized,omitempty"`
}

Session is Kratos's session as whoami returns it.

type SessionMethod

type SessionMethod struct {
	Method      string    `json:"method"`
	AAL         string    `json:"aal"`
	CompletedAt time.Time `json:"completed_at"`
	// Provider is the OIDC provider of an oidc method.
	Provider string `json:"provider,omitempty"`
}

SessionMethod is one factor of a session.

type Sessions

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

Sessions asks Kratos about a session on every call: no cache, so a revoked session fails the next call on every replica.

func NewSessions

func NewSessions(publicURL string, client *http.Client) (Sessions, error)

NewSessions asks Kratos's public API at publicURL (as this service reaches it); client nil: a client with a 10s timeout.

func (Sessions) Session

func (s Sessions) Session(ctx context.Context, c Credential) (Session, error)

Session returns the active session c proves, asking Kratos.

func (Sessions) Tokenize

func (s Sessions) Tokenize(ctx context.Context, c Credential, template string) (string, error)

Tokenize returns a token of the session c proves (template: the tokenizer template, "backplane" for backplane-kratos's): an edge that holds the browser's cookie can hand services a token instead.

func (Sessions) Verify

func (s Sessions) Verify(ctx context.Context, c Credential) (Auth, error)

Verify returns who c proves, asking Kratos.

type Tokens

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

Tokens verifies session tokens locally against the issuer'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 who it is.

type TokensOptions

type TokensOptions struct {
	// KeysURL is the public keys, backplane-kratos's
	// <public URL>/.well-known/jwks.json. Required.
	KeysURL string
	// Issuer is the iss tokens must carry: Kratos's public base URL as
	// Kratos knows it (serve.public.base_url). Empty: not checked.
	Issuer string
	// Audience is a value tokens' aud must hold. Empty: not checked (the
	// default template sets none).
	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