jwtprovider

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2025 License: Apache-2.0 Imports: 16 Imported by: 1

Documentation

Index

Constants

View Source
const (
	DefaultTTL      = time.Second * 86400 // 1 day
	DefaultIssuer   = "blueprint"
	DefaultAudience = "api"

	// common JWT signing algorithms
	HS256 = "HS256"
	HS384 = "HS384"
	HS512 = "HS512"
	RS256 = "RS256"
	RS384 = "RS384"
	RS512 = "RS512"
	ES256 = "ES256"
	ES384 = "ES384"
	ES512 = "ES512"
	EdDSA = "EdDSA"

	ErrSigningKeyRequired    = utils.Error("signing key is required")
	ErrPrivateKeyRequired    = utils.Error("private key is required")
	ErrPublicKeyRequired     = utils.Error("public key is required")
	ErrInvalidPrivateKey     = utils.Error("invalid private key format")
	ErrInvalidPrivateKeyType = utils.Error("invalid private key type")
	ErrInvalidPublicKey      = utils.Error("invalid public key format")
	ErrInvalidPublicKeyType  = utils.Error("invalid public key type")
	ErrInvalidDuration       = utils.Error("invalid expirationSeconds value")
	ErrInvalidMaxTokenSize   = utils.Error("invalid maxTokenSize")
)
View Source
const (
	ErrInvalidSigningAlgorithm = utils.Error("JWT signing algorithm is invalid")
	ErrInvalidToken            = utils.Error("invalid token")
	ErrTokenExpired            = utils.Error("token has expired")
	ErrMissingIssuer           = utils.Error("issuer validation failed")
	ErrMissingAudience         = utils.Error("audience validation failed")
	ErrNoRevocationManager     = utils.Error("revocation manager not available")
	ErrTokenParsingTimeout     = utils.Error("token parsing timeout")
	ErrTokenTooLarge           = utils.Error("token too large")
	ErrMaxSessionsExceeded     = utils.Error("maximum concurrent sessions exceeded")

	MaxJWTLength = 8192 // 8KB max
	MinJWTLength = 20   // Minimum viable JWT
)
View Source
const (

	// Common MapClaims fields
	ClaimIssuedAt  = "iat"
	ClaimIssuer    = "iss"
	ClaimSubject   = "sub"
	ClaimAudience  = "aud"
	ClaimExpiresAt = "exp"
	ClaimNotBefore = "nbf"
	ClaimJwtID     = "jti"
)
View Source
const (
	// Revocation-related errors
	ErrTokenAlreadyRevoked = utils.Error("token is already revoked")
	ErrInvalidTokenID      = utils.Error("invalid token ID")
	ErrRevocationFailed    = utils.Error("token revocation failed")
)
View Source
const (
	JWTIDLength = 32 // bytes of entropy
)

Variables

This section is empty.

Functions

func GenerateSecureJWTID added in v0.5.1

func GenerateSecureJWTID() (string, error)

GenerateSecureJWTID generates a cryptographically secure JWT ID

Types

type Claims

type Claims struct {
	jwt.RegisteredClaims
	Data map[string]any `json:"data,omitempty"`
}

Claims custom claims type

type JWTConfig

type JWTConfig struct {
	CfgSigningKey     *secure.DefaultCredentialConfig `json:"signingKey,omitempty"`   // SigningKey is the key used to sign JWT tokens
	CfgPrivateKey     *secure.KeyConfig               `json:"privateKey,omitempty"`   // PKCS#8 private key for asymmetric algorithms (RSA, ECDSA, EdDSA)
	CfgPublicKey      *secure.KeyConfig               `json:"publicKey,omitempty"`    // PEM PKIX public key for asymmetric algorithms (RSA, ECDSA, EdDSA)
	SigningAlgorithm  string                          `json:"signingAlgorithm"`       // SigningAlgorithm: HS256/HS384/HS512, RS256/RS384/RS512, ES256/ES384/ES512, EdDSA
	ExpirationSeconds int                             `json:"expirationSeconds"`      // ExpirationSeconds
	Issuer            string                          `json:"issuer"`                 // Issuer is the issuer of the token
	Audience          string                          `json:"audience"`               // Audience is the audience of the token
	KeyID             string                          `json:"keyID"`                  // KeyID for JWKS support
	MaxTokenSize      int                             `json:"maxTokenSize,omitempty"` // Max token size
	// Enhanced validation flags
	RequireIssuer   bool `json:"requireIssuer"`   // Mandatory issuer validation
	RequireAudience bool `json:"requireAudience"` // Mandatory audience validation

	// User token tracking
	TrackUserTokens bool `json:"trackUserTokens"`           // Enable user token tracking
	MaxUserSessions int  `json:"maxUserSessions,omitempty"` // Maximum concurrent sessions per user (0 = unlimited)
	// contains filtered or unexported fields
}

JWTConfig holds configuration for JWT tokens

func NewJWTConfig

func NewJWTConfig() *JWTConfig

NewJWTConfig returns a default JWT configuration

func NewJWTConfigWithKey

func NewJWTConfigWithKey(key []byte) (*JWTConfig, error)

NewJWTConfigWithKey default JWT config using a pre-defined key

func (*JWTConfig) Validate

func (c *JWTConfig) Validate() error

Validate the JWT configuration and assemble internal fields

type JWTParser

type JWTParser interface {
	ParseToken(tokenString string) (*Claims, error)
}

type JWTProvider

type JWTProvider interface {
	JWTParser
	JWTSigner
	JWTRevoker
	JWTRefresher
	GetRevocationManager() *RevocationManager
	GetActiveUserTokens(userID string) ([]string, error)
	RevokeAllUserTokens(userID string) error
	GetUserSessionCount(userID string) int
}

func NewProvider

func NewProvider(cfg *JWTConfig, opts ...ProviderOpts) (JWTProvider, error)

type JWTRefresher

type JWTRefresher interface {
	Refresh(string) (string, error)
}

type JWTRevoker

type JWTRevoker interface {
	RevokeToken(tokenString string) error
	RevokeTokenByID(tokenID string, expiresAt time.Time) error
	IsTokenRevoked(tokenID string) bool
}

type JWTSigner

type JWTSigner interface {
	GenerateToken(string, map[string]any) (string, error)
}

type MemoryRevocationBackend

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

MemoryRevocationBackend implements RevocationBackend using in-memory storage

func NewMemoryRevocationBackend

func NewMemoryRevocationBackend() *MemoryRevocationBackend

NewMemoryRevocationBackend creates a new in-memory revocation backend

func (*MemoryRevocationBackend) CleanupExpired

func (m *MemoryRevocationBackend) CleanupExpired() error

CleanupExpired removes expired revocation entries

func (*MemoryRevocationBackend) Close

func (m *MemoryRevocationBackend) Close() error

Close stops the cleanup process and releases resources

func (*MemoryRevocationBackend) GetRevokedTokens

func (m *MemoryRevocationBackend) GetRevokedTokens() ([]RevokedToken, error)

GetRevokedTokens returns all revoked tokens

func (*MemoryRevocationBackend) GetUserTokens added in v0.5.1

func (m *MemoryRevocationBackend) GetUserTokens(userID string) []string

GetUserTokens returns all active tokens for a user

func (*MemoryRevocationBackend) IsTokenRevoked

func (m *MemoryRevocationBackend) IsTokenRevoked(tokenID string) bool

IsTokenRevoked checks if a token is revoked

func (*MemoryRevocationBackend) RevokeAllUserTokens

func (m *MemoryRevocationBackend) RevokeAllUserTokens(userID string, issuedBefore time.Time) error

RevokeAllUserTokens revokes all tokens for a specific user

func (*MemoryRevocationBackend) RevokeToken

func (m *MemoryRevocationBackend) RevokeToken(tokenID string, expiresAt time.Time) error

RevokeToken revokes a token by its ID

func (*MemoryRevocationBackend) TrackUserToken

func (m *MemoryRevocationBackend) TrackUserToken(userID, tokenID string, expiresAt time.Time)

TrackUserToken associates a token with a user for bulk revocation

type ProviderOpts

type ProviderOpts func(*jwtProvider)

func WithRevocationManager

func WithRevocationManager(revocationManager *RevocationManager) ProviderOpts

type RevocationBackend

type RevocationBackend interface {
	// RevokeToken revokes a token by its ID with an optional expiration time
	RevokeToken(tokenID string, expiresAt time.Time) error

	// IsTokenRevoked checks if a token is revoked
	IsTokenRevoked(tokenID string) bool

	// RevokeAllUserTokens revokes all tokens for a specific user
	RevokeAllUserTokens(userID string, issuedBefore time.Time) error

	// GetRevokedTokens returns all revoked tokens (for admin purposes)
	GetRevokedTokens() ([]RevokedToken, error)

	// CleanupExpired removes expired revocation entries
	CleanupExpired() error

	// Close closes the backend and releases resources
	Close() error

	// TrackUserToken associates a token with a user
	TrackUserToken(userID, tokenID string, expiresAt time.Time)

	// GetUserTokens returns all active tokens for a user
	GetUserTokens(userID string) []string
}

RevocationBackend defines the interface for token revocation storage

type RevocationManager

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

RevocationManager manages token revocation

func NewRevocationManager

func NewRevocationManager(backend RevocationBackend) *RevocationManager

NewRevocationManager creates a new revocation manager

func (*RevocationManager) CleanupExpired

func (rm *RevocationManager) CleanupExpired() error

CleanupExpired removes expired revocation entries

func (*RevocationManager) Close

func (rm *RevocationManager) Close() error

Close closes the revocation manager and backend

func (*RevocationManager) GetRevokedTokens

func (rm *RevocationManager) GetRevokedTokens() ([]RevokedToken, error)

GetRevokedTokens returns all revoked tokens for admin purposes

func (*RevocationManager) IsTokenRevoked

func (rm *RevocationManager) IsTokenRevoked(tokenID string) bool

IsTokenRevoked checks if a token is revoked

func (*RevocationManager) RevokeAllUserTokens

func (rm *RevocationManager) RevokeAllUserTokens(userID string, issuedBefore time.Time) error

RevokeAllUserTokens revokes all tokens for a user issued before a specific time

func (*RevocationManager) RevokeToken

func (rm *RevocationManager) RevokeToken(tokenID string, expiresAt time.Time) error

RevokeToken revokes a specific token

type RevokedToken

type RevokedToken struct {
	TokenID   string    `json:"tokenId"`
	UserID    string    `json:"userId,omitempty"`
	RevokedAt time.Time `json:"revokedAt"`
	ExpiresAt time.Time `json:"expiresAt"`
}

RevokedToken represents a revoked token

type TokenMetadata added in v0.5.1

type TokenMetadata struct {
	TokenID   string    `json:"tokenId"`
	UserID    string    `json:"userId"`
	IssuedAt  time.Time `json:"issuedAt"`
	ExpiresAt time.Time `json:"expiresAt"`
	ClientIP  string    `json:"clientIP,omitempty"`  // For security audit
	UserAgent string    `json:"userAgent,omitempty"` // For device tracking
}

TokenMetadata represents metadata for an active token

Jump to

Keyboard shortcuts

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