Documentation
¶
Index ¶
- Constants
- Variables
- func RegisterSchema(s *schema.Schema) error
- type Algorithm
- type Audience
- type Claims
- type Config
- type Hooks
- func (h *Hooks) AfterIssue(fn func(ctx context.Context, tokenString string, claims *Claims) error)
- func (h *Hooks) AfterRevoke(fn func(ctx context.Context, jti string) error)
- func (h *Hooks) AfterVerify(fn func(ctx context.Context, claims *Claims) error)
- func (h *Hooks) BeforeIssue(fn func(ctx context.Context, claims *Claims) error)
- func (h *Hooks) BeforeRevoke(fn func(ctx context.Context, jti string) error)
- func (h *Hooks) BeforeVerify(fn func(ctx context.Context, tokenString string) error)
- type JWK
- type JWKS
- type JWT
- type Key
- func NewECDSAKey(id string, alg Algorithm, privKey *ecdsa.PrivateKey) (Key, error)
- func NewECDSAPublicKey(id string, alg Algorithm, pubKey *ecdsa.PublicKey) (Key, error)
- func NewEd25519Key(id string, privKey ed25519.PrivateKey) (Key, error)
- func NewEd25519PublicKey(id string, pubKey ed25519.PublicKey) (Key, error)
- func NewHMACKey(id string, alg Algorithm, secret []byte) (Key, error)
- func NewRSAKey(id string, alg Algorithm, privKey *rsa.PrivateKey) (Key, error)
- func NewRSAPublicKey(id string, alg Algorithm, pubKey *rsa.PublicKey) (Key, error)
- type KeyManager
- type KeyRotatedPayload
- type Module
- type NumericDate
- type Option
- func WithAllowedAlgorithms(algs ...Algorithm) Option
- func WithDefaultAudience(aud ...string) Option
- func WithDefaultLeeway(leeway time.Duration) Option
- func WithDefaultTTL(ttl time.Duration) Option
- func WithHooks(hooks *Hooks) Option
- func WithIssuer(issuer string) Option
- func WithKey(key Key) Option
- func WithKeyManager(km KeyManager) Option
- func WithRevocationCache(cache jwtcache.RevocationCache) Option
- type RevocationRecord
- type SubjectRevocationRecord
- type TokenIssuedPayload
- type TokenRevokedPayload
- type TokenVerifiedPayload
- type VerifyOption
Constants ¶
const ( // EventJWTTokenIssued is emitted when a new JWT has been signed and issued. EventJWTTokenIssued auth.EventName = "jwt.token.issued" // EventJWTTokenVerified is emitted when a token is successfully verified. EventJWTTokenVerified auth.EventName = "jwt.token.verified" // EventJWTTokenRevoked is emitted when a token or subject is explicitly revoked. EventJWTTokenRevoked auth.EventName = "jwt.token.revoked" // EventJWTKeyRotated is emitted when the active signing key is rotated. EventJWTKeyRotated auth.EventName = "jwt.key.rotated" )
const ( ModelJWTRevocations = "jwt_revocations" ModelJWTSubjectRevocations = "jwt_subject_revocations" )
Variables ¶
var ( // ErrInvalidToken is returned when a JWT is malformed, structurally invalid, or fails JSON parsing. ErrInvalidToken = errors.New("jwt: invalid or malformed token") // ErrTokenExpired is returned when a token's exp claim is in the past. ErrTokenExpired = errors.New("jwt: token has expired") // ErrTokenNotYetValid is returned when a token's nbf claim is in the future. ErrTokenNotYetValid = errors.New("jwt: token is not yet valid (nbf)") // ErrInvalidIssuer is returned when a token's iss claim does not match the expected issuer. ErrInvalidIssuer = errors.New("jwt: token issuer does not match expectation") // ErrInvalidAudience is returned when a token's aud claim does not include the expected audience. ErrInvalidAudience = errors.New("jwt: token audience does not match expectation") // ErrInvalidSubject is returned when a token's sub claim does not match the expected subject. ErrInvalidSubject = errors.New("jwt: token subject does not match expectation") // ErrAlgorithmMismatch is returned when a token header's alg differs from the key's declared algorithm, // preventing algorithm substitution attacks. ErrAlgorithmMismatch = errors.New("jwt: algorithm mismatch between token header and key specification") // ErrAlgorithmNotAllowed is returned when a token's algorithm is not among the configured allowed algorithms. ErrAlgorithmNotAllowed = errors.New("jwt: signing algorithm is not allowed") // ErrUnsignedTokenNotAllowed is returned when a token uses alg: 'none' or lacks a signature. ErrUnsignedTokenNotAllowed = errors.New("jwt: unsigned tokens (alg 'none') are strictly forbidden") // ErrInvalidSignature is returned when the cryptographic signature verification fails. ErrInvalidSignature = errors.New("jwt: cryptographic signature verification failed") // ErrKeyNotFound is returned when the key referenced by kid is not present in the KeyManager. ErrKeyNotFound = errors.New("jwt: signing key not found for specified kid") // ErrKeyIDRequired is returned when multiple keys are loaded but the token lacks a kid header. ErrKeyIDRequired = errors.New("jwt: kid header is required when multiple verification keys exist") // ErrInvalidKey is returned when the supplied cryptographic key is invalid, corrupt, or of wrong type. ErrInvalidKey = errors.New("jwt: invalid cryptographic key") // ErrNoActiveSigningKey is returned when issuing tokens without any active signing key configured. ErrNoActiveSigningKey = errors.New("jwt: no active signing key configured for token issuance") // ErrTokenRevoked is returned when the token has been explicitly invalidated in the revocation store. ErrTokenRevoked = errors.New("jwt: token has been revoked") // ErrMissingRequiredClaim is returned when a required claim is missing from the payload. ErrMissingRequiredClaim = errors.New("jwt: missing required claim") )
Functions ¶
func RegisterSchema ¶
RegisterSchema registers the JWT revocation models into the compiled schema.
Types ¶
type Algorithm ¶
type Algorithm string
Algorithm identifies a registered JWA cryptographic signing algorithm.
const ( // HMAC using SHA-256 HS256 Algorithm = "HS256" // HMAC using SHA-384 HS384 Algorithm = "HS384" // HMAC using SHA-512 HS512 Algorithm = "HS512" // RSASSA-PKCS1-v1_5 using SHA-256 RS256 Algorithm = "RS256" // RSASSA-PKCS1-v1_5 using SHA-384 RS384 Algorithm = "RS384" // RSASSA-PKCS1-v1_5 using SHA-512 RS512 Algorithm = "RS512" // RSASSA-PSS using SHA-256 PS256 Algorithm = "PS256" // RSASSA-PSS using SHA-384 PS384 Algorithm = "PS384" // RSASSA-PSS using SHA-512 PS512 Algorithm = "PS512" // ECDSA using P-256 and SHA-256 ES256 Algorithm = "ES256" // ECDSA using P-384 and SHA-384 ES384 Algorithm = "ES384" // ECDSA using P-521 and SHA-512 ES512 Algorithm = "ES512" // EdDSA using Ed25519 EdDSA Algorithm = "EdDSA" )
func (Algorithm) IsAsymmetric ¶
IsAsymmetric reports whether the algorithm is asymmetric (RSA, ECDSA, EdDSA).
func (Algorithm) IsSymmetric ¶
IsSymmetric reports whether the algorithm is symmetric (HMAC).
type Audience ¶
type Audience []string
Audience represents the aud claim which can be a single string or an array of strings in RFC 7519.
func (Audience) Contains ¶
Contains reports whether the target audience is present in the Audience slice.
func (Audience) MarshalJSON ¶
MarshalJSON serializes single audience as a JSON string, and multiple as an array.
func (*Audience) UnmarshalJSON ¶
UnmarshalJSON parses either a JSON string or an array of strings.
type Claims ¶
type Claims struct {
// Issuer (iss) identifies the principal that issued the JWT.
Issuer string `json:"iss,omitempty"`
// Subject (sub) identifies the principal that is the subject of the JWT.
Subject string `json:"sub,omitempty"`
// Audience (aud) identifies the recipients that the JWT is intended for.
Audience Audience `json:"aud,omitempty"`
// ExpiresAt (exp) identifies the expiration time on or after which the JWT MUST NOT be accepted.
ExpiresAt *NumericDate `json:"exp,omitempty"`
// NotBefore (nbf) identifies the time before which the JWT MUST NOT be accepted.
NotBefore *NumericDate `json:"nbf,omitempty"`
// IssuedAt (iat) identifies the time at which the JWT was issued.
IssuedAt *NumericDate `json:"iat,omitempty"`
// ID (jti) provides a unique identifier for the JWT.
ID string `json:"jti,omitempty"`
// Custom contains additional non-standard application claims.
Custom map[string]any `json:"-"`
}
Claims represents the standard and custom claims of a JWT payload.
func (Claims) MarshalJSON ¶
MarshalJSON serializes standard and custom claims into a single JSON object.
func (*Claims) UnmarshalJSON ¶
UnmarshalJSON deserializes standard claims and captures any remaining fields into Custom.
type Config ¶
type Config struct {
// Issuer defines the default issuer string applied to issued tokens.
Issuer string
// DefaultAudience specifies the default audience list applied when claims.Audience is empty.
DefaultAudience []string
// DefaultTTL specifies the default token validity duration when ExpiresAt is not explicitly provided.
DefaultTTL time.Duration
// AllowedAlgorithms is the strict whitelist of algorithms permitted for verification.
AllowedAlgorithms []Algorithm
// KeyManager manages cryptographic keys, key rotation, and kid resolution.
KeyManager KeyManager
// Cache accelerates revocation verification lookups.
Cache jwtcache.RevocationCache
// Leeway provides clock skew tolerance during expiration (exp) and not-before (nbf) validation.
Leeway time.Duration
// Hooks provides lifecycle extension points for issue, verify, and revoke operations.
Hooks *Hooks
}
Config configures the JWT plugin module.
type Hooks ¶
type Hooks struct {
// contains filtered or unexported fields
}
Hooks provides lifecycle extension points for JWT operations. Registered hooks execute synchronously and may mutate inputs or abort operations by returning an error.
func (*Hooks) AfterIssue ¶
AfterIssue registers an interceptor invoked after a token is signed.
func (*Hooks) AfterRevoke ¶
AfterRevoke registers an interceptor invoked after a token is revoked.
func (*Hooks) AfterVerify ¶
AfterVerify registers an interceptor invoked after a token is verified and validated.
func (*Hooks) BeforeIssue ¶
BeforeIssue registers an interceptor invoked before signing a token.
func (*Hooks) BeforeRevoke ¶
BeforeRevoke registers an interceptor invoked before revoking a token.
type JWK ¶
type JWK struct {
// Kty is the key type: RSA, EC, or OKP.
Kty string `json:"kty"`
// Use is the intended public key use: "sig".
Use string `json:"use,omitempty"`
// Kid is the key identifier.
Kid string `json:"kid,omitempty"`
// Alg is the algorithm intended for use with the key.
Alg string `json:"alg,omitempty"`
// Crv is the cryptographic curve for EC or OKP keys (e.g., "P-256", "Ed25519").
Crv string `json:"crv,omitempty"`
// X is the x coordinate for EC keys, or public key for OKP keys (base64url-encoded).
X string `json:"x,omitempty"`
// Y is the y coordinate for EC keys (base64url-encoded).
Y string `json:"y,omitempty"`
// N is the RSA modulus (base64url-encoded).
N string `json:"n,omitempty"`
// E is the RSA public exponent (base64url-encoded).
E string `json:"e,omitempty"`
}
JWK represents a single JSON Web Key per RFC 7517.
type JWKS ¶
type JWKS struct {
Keys []JWK `json:"keys"`
}
JWKS represents a JSON Web Key Set per RFC 7517.
func BuildJWKS ¶
func BuildJWKS(km KeyManager) (*JWKS, error)
BuildJWKS generates a JWKS from the given KeyManager, exporting only asymmetric public keys. Symmetric HMAC keys are strictly excluded to prevent secret disclosure.
type JWT ¶
type JWT interface {
// Issue signs and issues a new JWT token using the active signing key.
Issue(ctx context.Context, claims Claims) (string, error)
// IssueWithKey signs and issues a new JWT token using a specific key identifier (kid).
IssueWithKey(ctx context.Context, keyID string, claims Claims) (string, error)
// Verify parses the token, validates the cryptographic signature, validates standard claims
// (iss, aud, sub, exp, nbf), prevents algorithm confusion, and checks revocation if configured.
Verify(ctx context.Context, tokenString string, opts ...VerifyOption) (*Claims, error)
// Revoke invalidates a specific token identifier (jti) until its expiration time.
Revoke(ctx context.Context, jti string, expiresAt time.Time, reason string) error
// RevokeSubject invalidates all tokens issued to the given subject before the specified cutoff timestamp.
RevokeSubject(ctx context.Context, subject string, cutoff time.Time, reason string) error
// IsRevoked checks if a token or subject has been marked as revoked.
IsRevoked(ctx context.Context, jti string, subject string, issuedAt time.Time) (bool, error)
// JWKS exports the public keys formatted as an RFC 7517 JSON Web Key Set.
JWKS(ctx context.Context) (*JWKS, error)
// Keys returns the active KeyManager for key registration and rotation.
Keys() KeyManager
}
JWT defines the capability contract exposed by the JWT plugin module. Applications access it via auth.Get[plugins.JWT](app).
type Key ¶
type Key struct {
// ID uniquely identifies the key (kid).
ID string
// Algorithm declares the single cryptographic algorithm permitted for this key (alg).
Algorithm Algorithm
// Use defines the intended use of the key (typically "sig").
Use string
// PrivateKey contains the private key material (*rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey, or []byte).
// May be nil for verification-only keys.
PrivateKey any
// PublicKey contains the public key material (*rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey, or []byte for HMAC).
PublicKey any
// CreatedAt records when the key was created or added.
CreatedAt time.Time
}
Key represents a cryptographic key for JWT signing or verification.
func NewECDSAKey ¶
NewECDSAKey constructs an asymmetric ECDSA signing key.
func NewECDSAPublicKey ¶
NewECDSAPublicKey constructs an asymmetric ECDSA verification-only key.
func NewEd25519Key ¶
func NewEd25519Key(id string, privKey ed25519.PrivateKey) (Key, error)
NewEd25519Key constructs an Ed25519 signing key.
func NewEd25519PublicKey ¶
NewEd25519PublicKey constructs an Ed25519 verification-only key.
func NewHMACKey ¶
NewHMACKey constructs a symmetric key for HMAC algorithms.
func NewRSAPublicKey ¶
NewRSAPublicKey constructs an asymmetric RSA verification-only key.
type KeyManager ¶
type KeyManager interface {
// AddKey registers a key.
AddKey(key Key) error
// SetActiveSigningKey designates the default key ID used for signing.
SetActiveSigningKey(keyID string) error
// RotateSigningKey registers a new signing key and immediately designates it as active.
RotateSigningKey(newKey Key) error
// GetKey retrieves a key by its ID.
GetKey(keyID string) (Key, error)
// GetActiveSigningKey returns the active signing key.
GetActiveSigningKey() (Key, error)
// GetVerificationKey retrieves the matching key and enforces algorithm compatibility.
GetVerificationKey(kid string, requestedAlg Algorithm) (Key, error)
// ListKeys returns all registered keys.
ListKeys() []Key
// RemoveKey removes a key by ID.
RemoveKey(keyID string) error
}
KeyManager manages multiple keys, rotation, and active signing key designation.
func NewKeyManager ¶
func NewKeyManager() KeyManager
NewKeyManager initializes an empty, thread-safe KeyManager.
type KeyRotatedPayload ¶
type KeyRotatedPayload struct {
PreviousKeyID string `json:"previous_key_id,omitempty"`
NewKeyID string `json:"new_key_id"`
Algorithm Algorithm `json:"algorithm"`
Time time.Time `json:"time"`
}
KeyRotatedPayload carries metadata when a key rotation occurs.
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module implements auth.PluginModule for GoModularAuth JWT stateless tokens using plugin-sdk.
type NumericDate ¶
NumericDate represents a JSON numeric date (seconds since Unix epoch) per RFC 7519 section 2.
func NewNumericDate ¶
func NewNumericDate(t time.Time) *NumericDate
NewNumericDate creates a new NumericDate from a time.Time value, truncated to seconds.
func (*NumericDate) MarshalJSON ¶
func (n *NumericDate) MarshalJSON() ([]byte, error)
MarshalJSON marshals the timestamp as a Unix integer.
func (*NumericDate) UnmarshalJSON ¶
func (n *NumericDate) UnmarshalJSON(data []byte) error
UnmarshalJSON unmarshals a JSON number into a NumericDate.
type Option ¶
type Option func(*Config)
Option modifies a Config instance.
func WithAllowedAlgorithms ¶
WithAllowedAlgorithms configures the strict whitelist of algorithms permitted.
func WithDefaultAudience ¶
WithDefaultAudience sets the default audience list.
func WithDefaultLeeway ¶
WithDefaultLeeway sets the default clock skew leeway duration for token verification.
func WithDefaultTTL ¶
WithDefaultTTL configures the fallback token validity duration.
func WithIssuer ¶
WithIssuer configures the default issuer claim.
func WithRevocationCache ¶
func WithRevocationCache(cache jwtcache.RevocationCache) Option
WithRevocationCache sets the revocation cache.
type RevocationRecord ¶
type RevocationRecord struct {
JTI string `json:"jti"`
Subject string `json:"subject,omitempty"`
Reason string `json:"reason,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
RevokedAt time.Time `json:"revoked_at"`
}
RevocationRecord represents an explicit token revocation by unique ID (jti).
type SubjectRevocationRecord ¶
type SubjectRevocationRecord struct {
Subject string `json:"subject"`
Cutoff time.Time `json:"cutoff"`
Reason string `json:"reason,omitempty"`
RevokedAt time.Time `json:"revoked_at"`
}
SubjectRevocationRecord represents a blanket revocation for all tokens of a subject issued before Cutoff.
type TokenIssuedPayload ¶
type TokenIssuedPayload struct {
KeyID string `json:"key_id"`
JTI string `json:"jti,omitempty"`
Subject string `json:"subject,omitempty"`
Issuer string `json:"issuer,omitempty"`
Audience []string `json:"audience,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
IssuedAt time.Time `json:"issued_at,omitempty"`
}
TokenIssuedPayload carries diagnostic metadata about an issued token. Cryptographic keys, signatures, and sensitive claims are strictly omitted.
type TokenRevokedPayload ¶
type TokenRevokedPayload struct {
JTI string `json:"jti,omitempty"`
Subject string `json:"subject,omitempty"`
Reason string `json:"reason,omitempty"`
RevokedAt time.Time `json:"revoked_at"`
}
TokenRevokedPayload carries metadata about a revocation event.
type TokenVerifiedPayload ¶
type TokenVerifiedPayload struct {
KeyID string `json:"key_id"`
JTI string `json:"jti,omitempty"`
Subject string `json:"subject,omitempty"`
Issuer string `json:"issuer,omitempty"`
Time time.Time `json:"time"`
}
TokenVerifiedPayload carries diagnostic metadata about a verified token.
type VerifyOption ¶
type VerifyOption func(*verifyConfig)
VerifyOption configures claim validation parameters for Verify.
func WithExpectedAudience ¶
func WithExpectedAudience(expected string) VerifyOption
WithExpectedAudience asserts that the token's aud claim contains expected.
func WithExpectedIssuer ¶
func WithExpectedIssuer(expected string) VerifyOption
WithExpectedIssuer asserts that the token's iss claim matches expected.
func WithExpectedSubject ¶
func WithExpectedSubject(expected string) VerifyOption
WithExpectedSubject asserts that the token's sub claim matches expected.
func WithLeeway ¶
func WithLeeway(leeway time.Duration) VerifyOption
WithLeeway allows clock skew tolerance when validating exp and nbf timestamps.
func WithRequiredClaims ¶
func WithRequiredClaims(claims ...string) VerifyOption
WithRequiredClaims asserts that all specified claims are present in the token payload.