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
- Variables
- func GRPCCode(err error) codes.Code
- func HTTPStatus(err error) int
- func WithAuth(ctx context.Context, a Auth) context.Context
- type Address
- type Auth
- type Authenticator
- func (a Authenticator) Authenticate(ctx context.Context, h http.Header) (Auth, error)
- func (a Authenticator) Optional(next http.Handler) http.Handler
- func (a Authenticator) Required(next http.Handler) http.Handler
- func (a Authenticator) StreamInterceptor(required bool) grpc.StreamServerInterceptor
- func (a Authenticator) UnaryInterceptor(required bool) grpc.UnaryServerInterceptor
- type Credential
- type Device
- type ExpiredError
- type Identity
- type Session
- type SessionMethod
- type Sessions
- type Tokens
- type TokensOptions
Constants ¶
const ( // FromToken: verified from a token, locally. FromToken = "token" // FromSession: Kratos answered for the session. FromSession = "session" )
Source of an Auth.
const ( AAL1 = "aal1" AAL2 = "aal2" AAL3 = "aal3" )
Assurance levels, weakest first.
const DefaultCookie = "ory_kratos_session"
DefaultCookie is Kratos's session cookie name.
Variables ¶
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 = errors.New("auth: unavailable") )
Errors. Every error of the package wraps one of them.
var ErrOptions = errors.New("auth: options")
ErrOptions: an option is missing or wrong.
Functions ¶
func HTTPStatus ¶
HTTPStatus is the status a refusal for err answers with.
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 ¶
FromContext returns the Auth the middleware put into ctx.
func (Auth) AuthenticatedWithin ¶
AuthenticatedWithin reports whether the user proved who they are within d before now: a sensitive action asks for a fresh sign-in.
func (Auth) UsedMethod ¶
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 ¶
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 ¶
NewSessions asks Kratos's public API at publicURL (as this service reaches it); client nil: a client with a 10s timeout.
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.
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.