Documentation
¶
Index ¶
- Constants
- Variables
- type Clock
- type Config
- type Option
- func WithAudience(audience string) Option
- func WithCleanupInterval(interval time.Duration) Option
- func WithClock(clock Clock) Option
- func WithIssuer(issuer string) Option
- func WithLeeway(leeway time.Duration) Option
- func WithMaxTokenLifetime(lifetime time.Duration) Option
- func WithUserRevocationTTL(ttl time.Duration) Option
- type Service
- type Token
Constants ¶
const ( // MinSecretLength is the minimum required length for the secret key MinSecretLength = 32 // DefaultCleanupInterval is the default interval for cleaning up expired tokens DefaultCleanupInterval = 1 * time.Hour // DefaultUserRevocationTTL is the default TTL for user revocation records DefaultUserRevocationTTL = 30 * 24 * time.Hour // 30 days // DefaultMaxTokenLifetime is the default maximum token lifetime DefaultMaxTokenLifetime = 24 * time.Hour // 24 hours // DefaultLeeway is the default clock skew leeway for token validation DefaultLeeway = 2 * time.Minute )
Variables ¶
var ( ErrMissingSecretKey = errors.New("jwt: missing secret key") ErrWeakSecretKey = errors.New("jwt: secret key too weak") ErrEmptyUserID = errors.New("jwt: empty user ID") ErrTokenCreation = errors.New("jwt: failed to create token") ErrInvalidToken = errors.New("jwt: invalid token") ErrExpiredToken = errors.New("jwt: token has expired") ErrRevokedToken = errors.New("jwt: token has been revoked") ErrInvalidIssuer = errors.New("jwt: invalid issuer") ErrInvalidAudience = errors.New("jwt: invalid audience") ErrServiceClosed = errors.New("jwt: service is closed") )
Common JWT service errors
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// SecretKey is the key used for signing and verifying JWT tokens.
// This should be a secure random string with at least 32 bytes.
SecretKey string
// CleanupInterval specifies how often to cleanup expired revoked tokens.
// Defaults to 1 hour if not set or <= 0.
CleanupInterval time.Duration
// UserRevocationTTL specifies how long to keep user revocation records.
// Defaults to 30 days if not set or <= 0.
// For security, this should be >= MaxTokenLifetime to prevent revoked tokens
// from becoming valid again.
UserRevocationTTL time.Duration
// MaxTokenLifetime specifies the maximum allowed token lifetime.
// This is used to ensure UserRevocationTTL is set appropriately.
// Defaults to 24 hours if not set or <= 0.
MaxTokenLifetime time.Duration
// Leeway specifies the time window for clock skew tolerance.
// Tokens expiring within this window are still considered valid.
// Defaults to 2 minutes if not set or <= 0.
Leeway time.Duration
// Issuer is the JWT issuer claim (iss).
// If set, tokens will include this issuer and validation will check it.
Issuer string
// Audience is the JWT audience claim (aud).
// If set, tokens will include this audience and validation will check it.
Audience string
// Clock allows for time injection, mainly useful for testing.
// If not set, uses the standard time.Now().
Clock Clock
}
Config holds the configuration for JWT service.
type Option ¶
type Option func(*Config)
Option is a function that modifies the Config
func WithAudience ¶
WithAudience sets the JWT audience claim
func WithCleanupInterval ¶
WithCleanupInterval sets the cleanup interval for expired tokens
func WithLeeway ¶
WithLeeway sets the clock skew leeway for token validation
func WithMaxTokenLifetime ¶
WithMaxTokenLifetime sets the maximum token lifetime
func WithUserRevocationTTL ¶
WithUserRevocationTTL sets the TTL for user revocation records
type Service ¶
type Service interface {
// GenerateToken creates a new JWT token for the given user ID and roles.
// The token will expire after the specified duration.
GenerateToken(userID string, roles []string, expiresIn time.Duration) (string, error)
// ValidateToken validates a token string and returns the parsed token.
// It checks token signature, expiration, and revocation status.
ValidateToken(tokenString string) (*Token, error)
// ValidateAndParse validates a token and returns the parsed token in one step.
//
// Deprecated: will be removed in v3. Use ValidateToken instead.
ValidateAndParse(tokenString string) (*Token, error)
// RefreshToken invalidates the old token and generates a new one with the same claims.
// The new token will have a new expiration time calculated from the current time,
// preserving the original token's expiration duration.
RefreshToken(tokenString string) (string, error)
// RefreshTokenExtend invalidates the old token and generates a new one
// with the specified expiration duration from the current time.
// This provides an alternative refresh strategy.
RefreshTokenExtend(tokenString string, extendsIn time.Duration) (string, error)
// RevokeToken adds a token to the revocation list.
// Revoked tokens will fail validation.
RevokeToken(tokenString string) error
// IsTokenRevoked checks if an individual token is in the revocation list.
// Note: this only checks token-level revocations added via RevokeToken.
// It does NOT check user-level revocations from RevokeAllUserTokens.
// Use ValidateToken for full revocation checks including user-level revocations.
IsTokenRevoked(tokenID string) bool
// ParseToken parses a token without fully validating it.
// This method extracts claims even from expired tokens.
ParseToken(tokenString string) (*Token, error)
// RevokeAllUserTokens revokes all tokens for a specific user.
// Any token issued before the revocation time will be considered invalid.
RevokeAllUserTokens(userID string) error
// Close terminates any background processes of the service.
// Should be called when the service is no longer needed.
Close()
}
Service defines the interface for JWT token management operations. This interface provides a complete JWT service with token generation, validation, refresh, and revocation capabilities.
func New ¶
New creates a new JWT service with the provided secret key and options.
Security Requirements: - secretKey must be at least 32 characters long and securely randomly generated - Use a cryptographically secure random generator for production keys - Store the secret key securely (environment variables, secret management systems)
Example:
service, err := New("your-super-secure-secret-key-here",
WithCleanupInterval(30*time.Minute),
WithIssuer("your-app"),
WithAudience("your-users"))
type Token ¶
type Token struct {
UserID string `json:"user_id"`
Roles []string `json:"roles"`
ExpiresAt time.Time `json:"expires_at"`
IssuedAt time.Time `json:"issued_at"`
NotBefore time.Time `json:"not_before,omitempty"`
TokenID string `json:"token_id"`
Issuer string `json:"issuer,omitempty"`
Audience string `json:"audience,omitempty"`
Subject string `json:"subject,omitempty"` // Maps to UserID for compatibility
Raw string `json:"raw,omitempty"` // Original token string
}
Token represents a parsed JWT token with its claims.