Documentation
¶
Overview ¶
Package auth provides JWT (JSON Web Token) authentication and authorization.
This package implements JWT token generation, validation, and refresh functionality with support for both HMAC and RSA signing algorithms. It integrates with the RBAC system for permission-based access control.
Overview ¶
The auth package provides two main components:
- JWTManager: Handles token issuance, validation, refresh, and blacklisting
- TokenBlacklist: Manages revoked tokens for logout functionality
JWT tokens contain standard claims (subject, issuer, audience, expiration) plus custom claims for roles and permissions from the RBAC system.
Token Generation ¶
Generate access/refresh token pairs for authenticated users:
jwtManager := auth.NewJWTManager(auth.JWTConfig{
SigningKey: []byte("your-secret-key"),
Issuer: "your-app",
Audience: "your-api",
AccessTokenTTL: 15 * time.Minute,
RefreshTokenTTL: 7 * 24 * time.Hour,
}, rbac)
tokens, err := jwtManager.GenerateToken(ctx, "user123", "user@example.com", nil)
Token Validation ¶
Validate tokens in HTTP handlers or middleware:
claims, err := jwtManager.ValidateToken(tokenString)
if err != nil {
return err // invalid/expired token
}
Token Refresh ¶
Refresh expired access tokens using refresh tokens:
newTokens, err := jwtManager.RefreshTokens(refreshToken)
Token Invalidation (Logout) ¶
Invalidate tokens for logout using the blacklist:
blacklist := auth.NewTokenBlacklist() jwtManager.SetBlacklist(blacklist) jwtManager.InvalidateToken(accessToken)
RSA Support ¶
For production environments, use RSA keys for enhanced security:
rsaMaker, _ := auth.NewRSAJWTMaker(2048)
accessToken, _ := rsaMaker.CreateToken("user123")
claims, _ := rsaMaker.VerifyToken(accessToken)
Security Considerations ¶
- Always use RS256 (RSA) in production with key rotation
- Keep signing keys secure; never log or expose them
- Set appropriate token TTLs (shorter access, longer refresh)
- Implement token rotation on privilege escalation
- Use the blacklist for sensitive operations (password change, logout)
Index ¶
- Variables
- func GenerateKeyPair(bits int) (*rsa.PrivateKey, error)
- func GenerateRandomState() string
- func GenerateSecureToken(length int) string
- func GetJWTField(tokenString, field string) (interface{}, error)
- func GetUserID(ctx context.Context) string
- func NewInMemoryAPIKeyStore() *inMemoryAPIKeyStore
- func NewInMemoryAuditLogger(maxSize int) *inMemoryAuditLogger
- func ParseJWTExpiry(tokenString string) (time.Time, error)
- func ParseJWTIssuedAt(tokenString string) (time.Time, error)
- func VerifyState(expected, actual string) bool
- func WithRole(ctx context.Context, role Role) context.Context
- func WithUserID(ctx context.Context, userID string) context.Context
- type APIKey
- type APIKeyKeyConfig
- type APIKeyManager
- func (m *APIKeyManager) CreateKey(ctx context.Context, name string, permissions, roles []string, tenantID string, ...) (*CreatedAPIKey, error)
- func (m *APIKeyManager) GetKey(ctx context.Context, id string) (*APIKey, error)
- func (m *APIKeyManager) ListKeys(ctx context.Context, tenantID string) ([]*APIKey, error)
- func (m *APIKeyManager) RevokeKey(ctx context.Context, id string) error
- func (m *APIKeyManager) ValidateKey(ctx context.Context, rawKey string) (*APIKey, error)
- type APIKeyStore
- type AuditEvent
- type AuditEventType
- type AuditFilter
- type AuditLogger
- type AuditRecorder
- func (r *AuditRecorder) Query(ctx context.Context, filter AuditFilter) ([]AuditEvent, error)
- func (r *AuditRecorder) RecordAPIKeyUsed(ctx context.Context, keyID, tenantID, ipAddress string, success bool)
- func (r *AuditRecorder) RecordAuthFailure(ctx context.Context, userID, reason, ipAddress string)
- func (r *AuditRecorder) RecordLogin(ctx context.Context, userID, tenantID, ipAddress, userAgent string, ...)
- func (r *AuditRecorder) RecordLogout(ctx context.Context, userID, tenantID string)
- func (r *AuditRecorder) RecordPermissionDenied(ctx context.Context, userID, permission, resource string)
- func (r *AuditRecorder) RecordTokenRefresh(ctx context.Context, userID, tenantID string)
- type CachedRoleStore
- type CreatedAPIKey
- type DatabaseRoleStore
- type JWTConfig
- type JWTMaker
- type JWTManager
- func (j *JWTManager) GenerateToken(ctx context.Context, userID, email string, roles []string) (*TokenPair, error)
- func (j *JWTManager) GenerateTokenWithTenant(ctx context.Context, userID, email, tenantID string, roles []string, ...) (*TokenPair, error)
- func (j *JWTManager) InvalidateToken(tokenString string) error
- func (j *JWTManager) RefreshTokens(refreshToken string) (*TokenPair, error)
- func (j *JWTManager) SetBlacklist(blacklist *TokenBlacklist)
- func (j *JWTManager) ValidateToken(tokenString string) (*TokenClaims, error)
- type Permission
- type RBAC
- func (r *RBAC) AddPermissionToRole(role Role, perm Permission)
- func (r *RBAC) CheckPermission(ctx context.Context, userID string, perm Permission) error
- func (r *RBAC) ClearAllRoleCaches()
- func (r *RBAC) GRPCRequireAnyPermission(perms ...Permission) grpc.UnaryServerInterceptor
- func (r *RBAC) GRPCRequirePermission(perm Permission) grpc.UnaryServerInterceptor
- func (r *RBAC) GRPCRequireRole(roles ...Role) grpc.UnaryServerInterceptor
- func (r *RBAC) GetEffectivePermissions(role Role) []Permission
- func (r *RBAC) GetRole(ctx context.Context, userID string) (Role, error)
- func (r *RBAC) GetRoleHierarchy(role Role) []Role
- func (r *RBAC) GetUserPermissions(ctx context.Context, userID string) ([]Permission, error)
- func (r *RBAC) HasAllPermissions(role Role, perms ...Permission) bool
- func (r *RBAC) HasAnyPermission(role Role, perms ...Permission) bool
- func (r *RBAC) HasPermission(role Role, perm Permission) bool
- func (r *RBAC) InvalidateRoleCache(userID string)
- func (r *RBAC) RemovePermissionFromRole(role Role, perm Permission)
- func (r *RBAC) RequireAllPermissions(perms ...Permission) func(http.Handler) http.Handler
- func (r *RBAC) RequireAnyPermission(perms ...Permission) func(http.Handler) http.Handler
- func (r *RBAC) RequirePermission(perm Permission) func(http.Handler) http.Handler
- func (r *RBAC) RequireRole(roles ...Role) func(http.Handler) http.Handler
- func (r *RBAC) SetRoleHierarchy(role Role, parentRoles []Role)
- func (r *RBAC) SetRolePermissions(role Role, permissions []Permission)
- func (r *RBAC) SetRoleStore(store RoleStore)
- type RSAJWTMaker
- func (m *RSAJWTMaker) CreateToken(username string) (string, error)
- func (m *RSAJWTMaker) PrivateKey() *rsa.PrivateKey
- func (m *RSAJWTMaker) PrivateKeyPEM() ([]byte, error)
- func (m *RSAJWTMaker) PublicKey() *rsa.PublicKey
- func (m *RSAJWTMaker) PublicKeyPEM() ([]byte, error)
- func (m *RSAJWTMaker) SetTokenDuration(d time.Duration)
- func (m *RSAJWTMaker) VerifyToken(tokenString string) (*jwt.RegisteredClaims, error)
- type RedisClient
- type Role
- type RoleStore
- type RotationConfig
- type TokenBlacklist
- type TokenClaims
- type TokenPair
- type TokenRotation
Constants ¶
This section is empty.
Variables ¶
Functions ¶
func GenerateKeyPair ¶ added in v0.1.3
func GenerateKeyPair(bits int) (*rsa.PrivateKey, error)
GenerateKeyPair generates an RSA key pair.
func GenerateRandomState ¶ added in v0.1.3
func GenerateRandomState() string
GenerateRandomState generates a random state string for OAuth flows.
func GenerateSecureToken ¶ added in v0.1.3
GenerateSecureToken generates a cryptographically secure random token. Used for CSRF protection, OAuth state, etc.
func GetJWTField ¶ added in v0.1.3
GetJWTField extracts a field from the token payload without validation.
func NewInMemoryAPIKeyStore ¶ added in v0.1.43
func NewInMemoryAPIKeyStore() *inMemoryAPIKeyStore
func NewInMemoryAuditLogger ¶ added in v0.1.43
func NewInMemoryAuditLogger(maxSize int) *inMemoryAuditLogger
func ParseJWTExpiry ¶ added in v0.1.3
ParseJWTExpiry extracts the expiration time from a token without validation.
func ParseJWTIssuedAt ¶ added in v0.1.3
ParseJWTIssuedAt extracts the issued-at time from a token without validation.
func VerifyState ¶ added in v0.1.3
VerifyState verifies OAuth state strings using constant-time comparison.
Types ¶
type APIKeyKeyConfig ¶ added in v0.1.43
type APIKeyKeyConfig struct {
Store APIKeyStore
KeyPrefix string
KeyLength int
}
type APIKeyManager ¶ added in v0.1.43
type APIKeyManager struct {
// contains filtered or unexported fields
}
func NewAPIKeyManager ¶ added in v0.1.43
func NewAPIKeyManager(store APIKeyKeyConfig) *APIKeyManager
func (*APIKeyManager) CreateKey ¶ added in v0.1.43
func (m *APIKeyManager) CreateKey(ctx context.Context, name string, permissions, roles []string, tenantID string, ttl time.Duration) (*CreatedAPIKey, error)
func (*APIKeyManager) RevokeKey ¶ added in v0.1.43
func (m *APIKeyManager) RevokeKey(ctx context.Context, id string) error
func (*APIKeyManager) ValidateKey ¶ added in v0.1.43
type APIKeyStore ¶ added in v0.1.43
type APIKeyStore interface {
Create(ctx context.Context, key *APIKey) error
Get(ctx context.Context, id string) (*APIKey, error)
GetByHash(ctx context.Context, keyHash string) (*APIKey, error)
List(ctx context.Context, tenantID string) ([]*APIKey, error)
Revoke(ctx context.Context, id string) error
Delete(ctx context.Context, id string) error
UpdateLastUsed(ctx context.Context, id string) error
}
type AuditEvent ¶ added in v0.1.43
type AuditEvent struct {
Type AuditEventType `json:"type"`
Timestamp time.Time `json:"timestamp"`
UserID string `json:"user_id,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
func (AuditEvent) String ¶ added in v0.1.43
func (e AuditEvent) String() string
func (AuditEvent) ToJSON ¶ added in v0.1.43
func (e AuditEvent) ToJSON() (string, error)
type AuditEventType ¶ added in v0.1.43
type AuditEventType string
const ( EventLogin AuditEventType = "login" EventLogout AuditEventType = "logout" EventTokenRefresh AuditEventType = "token_refresh" EventTokenInvalidate AuditEventType = "token_invalidate" EventPermissionDenied AuditEventType = "permission_denied" EventRoleChange AuditEventType = "role_change" EventAPIKeyCreated AuditEventType = "api_key_created" EventAPIKeyRevoked AuditEventType = "api_key_revoked" EventAPIKeyUsed AuditEventType = "api_key_used" EventAuthFailure AuditEventType = "auth_failure" )
type AuditFilter ¶ added in v0.1.43
type AuditLogger ¶ added in v0.1.43
type AuditLogger interface {
Log(ctx context.Context, event AuditEvent)
Query(ctx context.Context, filter AuditFilter) ([]AuditEvent, error)
}
type AuditRecorder ¶ added in v0.1.43
type AuditRecorder struct {
// contains filtered or unexported fields
}
func NewAuditRecorder ¶ added in v0.1.43
func NewAuditRecorder(logger AuditLogger) *AuditRecorder
func (*AuditRecorder) Query ¶ added in v0.1.43
func (r *AuditRecorder) Query(ctx context.Context, filter AuditFilter) ([]AuditEvent, error)
func (*AuditRecorder) RecordAPIKeyUsed ¶ added in v0.1.43
func (r *AuditRecorder) RecordAPIKeyUsed(ctx context.Context, keyID, tenantID, ipAddress string, success bool)
func (*AuditRecorder) RecordAuthFailure ¶ added in v0.1.43
func (r *AuditRecorder) RecordAuthFailure(ctx context.Context, userID, reason, ipAddress string)
func (*AuditRecorder) RecordLogin ¶ added in v0.1.43
func (*AuditRecorder) RecordLogout ¶ added in v0.1.43
func (r *AuditRecorder) RecordLogout(ctx context.Context, userID, tenantID string)
func (*AuditRecorder) RecordPermissionDenied ¶ added in v0.1.43
func (r *AuditRecorder) RecordPermissionDenied(ctx context.Context, userID, permission, resource string)
func (*AuditRecorder) RecordTokenRefresh ¶ added in v0.1.43
func (r *AuditRecorder) RecordTokenRefresh(ctx context.Context, userID, tenantID string)
type CachedRoleStore ¶
type CachedRoleStore struct {
// contains filtered or unexported fields
}
CachedRoleStore wraps a RoleStore with in-memory caching
func NewCachedRoleStore ¶
func NewCachedRoleStore(store RoleStore, ttl time.Duration) *CachedRoleStore
NewCachedRoleStore creates a new cached role store with the specified TTL
func (*CachedRoleStore) ClearCache ¶
func (s *CachedRoleStore) ClearCache()
ClearCache clears all cached roles
func (*CachedRoleStore) GetUserRole ¶
GetUserRole retrieves the user role from cache or backing store
func (*CachedRoleStore) InvalidateCache ¶
func (s *CachedRoleStore) InvalidateCache(userID string)
InvalidateCache invalidates the cached role for a specific user
func (*CachedRoleStore) Stop ¶ added in v0.1.2
func (s *CachedRoleStore) Stop()
Stop stops the background cleanup goroutine
type CreatedAPIKey ¶ added in v0.1.43
type DatabaseRoleStore ¶
type DatabaseRoleStore struct {
// contains filtered or unexported fields
}
DatabaseRoleStore implements RoleStore for database-backed role retrieval
func NewDatabaseRoleStore ¶
func NewDatabaseRoleStore(getRole func(ctx context.Context, userID string) (Role, error)) *DatabaseRoleStore
NewDatabaseRoleStore creates a new database-backed role store
func (*DatabaseRoleStore) GetUserRole ¶
GetUserRole retrieves the user role from the database
type JWTConfig ¶ added in v0.1.3
type JWTConfig struct {
SigningKey []byte // Secret key for HMAC signing (HS256/HS384/HS512)
PublicKey *rsa.PublicKey // RSA public key for RS256 verification
PrivateKey *rsa.PrivateKey // RSA private key for RS256 signing
Algorithm string // Signing algorithm: "HS256", "HS384", "HS512", "RS256"
Issuer string // Token issuer (iss claim)
Audience string // Expected audience (aud claim)
AccessTokenTTL time.Duration // Access token lifetime (default: 15 minutes)
RefreshTokenTTL time.Duration // Refresh token lifetime (default: 7 days)
}
JWTConfig holds configuration for JWT token operations.
type JWTMaker ¶ added in v0.1.3
type JWTMaker struct {
// contains filtered or unexported fields
}
JWTMaker provides simple HMAC-based JWT operations. Suitable for development or simple use cases.
func NewJWTMaker ¶ added in v0.1.3
NewJWTMaker creates a JWTMaker with the given secret key.
func (*JWTMaker) CreateToken ¶ added in v0.1.3
CreateToken creates a JWT with the username as subject.
func (*JWTMaker) SetTokenDuration ¶ added in v0.1.3
SetTokenDuration sets the token duration.
func (*JWTMaker) VerifyToken ¶ added in v0.1.3
func (m *JWTMaker) VerifyToken(tokenString string) (*jwt.RegisteredClaims, error)
VerifyToken verifies and returns claims from a token.
type JWTManager ¶ added in v0.1.3
type JWTManager struct {
// contains filtered or unexported fields
}
JWTManager handles JWT token generation, validation, and refresh.
func NewJWTManager ¶ added in v0.1.3
func NewJWTManager(config JWTConfig, rbac *RBAC) *JWTManager
NewJWTManager creates a new JWT manager with the given configuration. If rbac is provided, permissions will be automatically loaded from RBAC on token generation. Default TTLs: AccessToken=15min, RefreshToken=7 days. Default algorithm: HS256.
func (*JWTManager) GenerateToken ¶ added in v0.1.3
func (j *JWTManager) GenerateToken(ctx context.Context, userID, email string, roles []string) (*TokenPair, error)
GenerateToken creates a new access/refresh token pair for a user. If roles is nil and rbac is configured, permissions are loaded from RBAC.
func (*JWTManager) GenerateTokenWithTenant ¶ added in v0.1.3
func (j *JWTManager) GenerateTokenWithTenant(ctx context.Context, userID, email, tenantID string, roles []string, metadata map[string]string) (*TokenPair, error)
GenerateTokenWithTenant creates tokens with tenant context for multi-tenant applications.
func (*JWTManager) InvalidateToken ¶ added in v0.1.3
func (j *JWTManager) InvalidateToken(tokenString string) error
InvalidateToken adds a token to the blacklist for logout.
func (*JWTManager) RefreshTokens ¶ added in v0.1.3
func (j *JWTManager) RefreshTokens(refreshToken string) (*TokenPair, error)
RefreshTokens creates new access/refresh tokens using a valid refresh token.
func (*JWTManager) SetBlacklist ¶ added in v0.1.3
func (j *JWTManager) SetBlacklist(blacklist *TokenBlacklist)
SetBlacklist sets the token blacklist for logout support.
func (*JWTManager) ValidateToken ¶ added in v0.1.3
func (j *JWTManager) ValidateToken(tokenString string) (*TokenClaims, error)
ValidateToken validates a token string and returns the claims. Validates: signature, expiration, issuer, audience, and blacklist.
type Permission ¶
type Permission string
Permission represents a specific permission in the system
const ( // Wallet permissions PermWalletRead Permission = "wallet:read" PermWalletWrite Permission = "wallet:write" PermWalletDelete Permission = "wallet:delete" // Portfolio permissions PermPortfolioRead Permission = "portfolio:read" PermPortfolioWrite Permission = "portfolio:write" PermPortfolioDelete Permission = "portfolio:delete" // Analytics permissions PermAnalyticsRead Permission = "analytics:read" PermAnalyticsAdvanced Permission = "analytics:advanced" // Billing permissions PermBillingRead Permission = "billing:read" PermBillingWrite Permission = "billing:write" PermBillingDelete Permission = "billing:delete" // User permissions PermUserRead Permission = "user:read" PermUserWrite Permission = "user:write" PermUserDelete Permission = "user:delete" // Admin permissions PermAdminRead Permission = "admin:read" PermAdminWrite Permission = "admin:write" PermAdminDelete Permission = "admin:delete" // API permissions PermAPICreate Permission = "api:create" PermAPIRead Permission = "api:read" PermAPIWrite Permission = "api:write" PermAPIDelete Permission = "api:delete" // Workflow permissions PermWorkflowCreate Permission = "workflow:create" PermWorkflowRead Permission = "workflow:read" PermWorkflowWrite Permission = "workflow:write" PermWorkflowDelete Permission = "workflow:delete" // ZK proof permissions PermZKCreate Permission = "zk:create" PermZKRead Permission = "zk:read" PermZKVerify Permission = "zk:verify" )
type RBAC ¶
type RBAC struct {
// contains filtered or unexported fields
}
RBAC handles role-based access control
func NewRBAC ¶
NewRBAC creates a new RBAC instance with default role permissions If a roleStore is provided, it will be used for database-backed role retrieval. If nil, a default in-memory role store will be used (returns RoleUser for all users).
func (*RBAC) AddPermissionToRole ¶
func (r *RBAC) AddPermissionToRole(role Role, perm Permission)
AddPermissionToRole adds a permission to a role
func (*RBAC) CheckPermission ¶
CheckPermission checks if a user has a specific permission
func (*RBAC) ClearAllRoleCaches ¶
func (r *RBAC) ClearAllRoleCaches()
ClearAllRoleCaches clears all cached role data
func (*RBAC) GRPCRequireAnyPermission ¶
func (r *RBAC) GRPCRequireAnyPermission(perms ...Permission) grpc.UnaryServerInterceptor
GRPCRequireAnyPermission creates a gRPC interceptor that requires any of the specified permissions
func (*RBAC) GRPCRequirePermission ¶
func (r *RBAC) GRPCRequirePermission(perm Permission) grpc.UnaryServerInterceptor
GRPCRequirePermission creates a gRPC interceptor that requires a specific permission
func (*RBAC) GRPCRequireRole ¶
func (r *RBAC) GRPCRequireRole(roles ...Role) grpc.UnaryServerInterceptor
GRPCRequireRole creates a gRPC interceptor that requires a specific role
func (*RBAC) GetEffectivePermissions ¶ added in v0.1.43
func (r *RBAC) GetEffectivePermissions(role Role) []Permission
GetEffectivePermissions returns all permissions for a role including inherited ones
func (*RBAC) GetRole ¶
GetRole retrieves the role for a user from the role store It uses the configured RoleStore (database, cache, etc.) for role lookup
func (*RBAC) GetRoleHierarchy ¶ added in v0.1.43
GetRoleHierarchy returns parent roles for a role
func (*RBAC) GetUserPermissions ¶
GetUserPermissions retrieves all permissions for a user
func (*RBAC) HasAllPermissions ¶
func (r *RBAC) HasAllPermissions(role Role, perms ...Permission) bool
HasAllPermissions checks if a role has all of the specified permissions
func (*RBAC) HasAnyPermission ¶
func (r *RBAC) HasAnyPermission(role Role, perms ...Permission) bool
HasAnyPermission checks if a role has any of the specified permissions
func (*RBAC) HasPermission ¶
func (r *RBAC) HasPermission(role Role, perm Permission) bool
HasPermission checks if a role has a specific permission It also checks inherited permissions from parent roles in the hierarchy
func (*RBAC) InvalidateRoleCache ¶
InvalidateRoleCache invalidates any cached role data for a specific user This is useful when a user's role changes
func (*RBAC) RemovePermissionFromRole ¶
func (r *RBAC) RemovePermissionFromRole(role Role, perm Permission)
RemovePermissionFromRole removes a permission from a role
func (*RBAC) RequireAllPermissions ¶
RequireAllPermissions creates an HTTP middleware that requires all of the specified permissions
func (*RBAC) RequireAnyPermission ¶
RequireAnyPermission creates an HTTP middleware that requires any of the specified permissions
func (*RBAC) RequirePermission ¶
RequirePermission creates an HTTP middleware that requires a specific permission
func (*RBAC) RequireRole ¶
RequireRole creates an HTTP middleware that requires a specific role
func (*RBAC) SetRoleHierarchy ¶ added in v0.1.43
SetRoleHierarchy sets parent roles for a role
func (*RBAC) SetRolePermissions ¶
func (r *RBAC) SetRolePermissions(role Role, permissions []Permission)
SetRolePermissions allows customizing permissions for a role
func (*RBAC) SetRoleStore ¶
SetRoleStore sets the role store for role retrieval
type RSAJWTMaker ¶ added in v0.1.3
type RSAJWTMaker struct {
// contains filtered or unexported fields
}
RSAJWTMaker provides RSA-based JWT operations. Recommended for production use with proper key management.
func NewRSAJWTMaker ¶ added in v0.1.3
func NewRSAJWTMaker(bits int) (*RSAJWTMaker, error)
NewRSAJWTMaker creates a new RSA JWT maker with the specified key size. Common key sizes: 2048 (recommended), 4096 (high security).
func (*RSAJWTMaker) CreateToken ¶ added in v0.1.3
func (m *RSAJWTMaker) CreateToken(username string) (string, error)
CreateToken creates a JWT with the username as subject using RSA.
func (*RSAJWTMaker) PrivateKey ¶ added in v0.1.3
func (m *RSAJWTMaker) PrivateKey() *rsa.PrivateKey
PrivateKey returns the RSA private key.
func (*RSAJWTMaker) PrivateKeyPEM ¶ added in v0.1.3
func (m *RSAJWTMaker) PrivateKeyPEM() ([]byte, error)
PrivateKeyPEM returns the private key in PEM format.
func (*RSAJWTMaker) PublicKey ¶ added in v0.1.3
func (m *RSAJWTMaker) PublicKey() *rsa.PublicKey
PublicKey returns the RSA public key.
func (*RSAJWTMaker) PublicKeyPEM ¶ added in v0.1.3
func (m *RSAJWTMaker) PublicKeyPEM() ([]byte, error)
PublicKeyPEM returns the public key in PEM format.
func (*RSAJWTMaker) SetTokenDuration ¶ added in v0.1.3
func (m *RSAJWTMaker) SetTokenDuration(d time.Duration)
SetTokenDuration sets the token duration.
func (*RSAJWTMaker) VerifyToken ¶ added in v0.1.3
func (m *RSAJWTMaker) VerifyToken(tokenString string) (*jwt.RegisteredClaims, error)
VerifyToken verifies and returns claims from an RSA-signed token.
type RedisClient ¶ added in v0.1.3
type RedisClient interface {
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
Get(ctx context.Context, key string) (string, error)
Del(ctx context.Context, keys ...string) error
Exists(ctx context.Context, keys ...string) (int, error)
}
RedisClient interface for Redis-backed blacklist.
type RoleStore ¶
type RoleStore interface {
// GetUserRole retrieves the role for a user from the data source
GetUserRole(ctx context.Context, userID string) (Role, error)
}
RoleStore defines the interface for retrieving user roles from a data source
type RotationConfig ¶ added in v0.1.43
type RotationConfig struct {
EnableRotation bool
RotationThreshold time.Duration
MaxRefreshCount int
RotationKeyBuilder func(*JWTManager) interface{}
}
type TokenBlacklist ¶ added in v0.1.3
type TokenBlacklist struct {
// contains filtered or unexported fields
}
TokenBlacklist stores invalidated token IDs for logout functionality. Supports both in-memory and Redis-backed storage.
func NewTokenBlacklist ¶ added in v0.1.3
func NewTokenBlacklist() *TokenBlacklist
NewTokenBlacklist creates a new in-memory token blacklist.
func (*TokenBlacklist) Blacklist ¶ added in v0.1.3
func (b *TokenBlacklist) Blacklist(tokenID string, ttl time.Duration) error
Blacklist adds a token ID to the blacklist.
func (*TokenBlacklist) CleanExpired ¶ added in v0.1.3
func (b *TokenBlacklist) CleanExpired()
CleanExpired removes expired entries from in-memory blacklist.
func (*TokenBlacklist) IsBlacklisted ¶ added in v0.1.3
func (b *TokenBlacklist) IsBlacklisted(tokenID string) (bool, error)
IsBlacklisted checks if a token ID is in the blacklist.
func (*TokenBlacklist) SetRedisClient ¶ added in v0.1.3
func (b *TokenBlacklist) SetRedisClient(client RedisClient)
SetRedisClient configures a Redis client for distributed blacklist.
type TokenClaims ¶ added in v0.1.3
type TokenClaims struct {
jwt.RegisteredClaims // Standard claims (iat, exp, sub, iss, aud, etc.)
UserID string `json:"user_id"` // User identifier
Email string `json:"email"` // User email address
Roles []string `json:"roles"` // User roles
Permissions []string `json:"permissions"` // User permissions
TenantID string `json:"tenant_id,omitempty"` // Multi-tenant identifier
Metadata map[string]string `json:"metadata,omitempty"` // Additional metadata
}
TokenClaims represents custom JWT claims including user identity and permissions.
type TokenPair ¶ added in v0.1.3
type TokenPair struct {
AccessToken string `json:"access_token"` // JWT for API access
RefreshToken string `json:"refresh_token"` // Long-lived token for refresh
ExpiresAt int64 `json:"expires_at"` // Unix timestamp when access token expires
TokenType string `json:"token_type"` // Always "Bearer"
}
TokenPair represents an issued access/refresh token pair.
type TokenRotation ¶ added in v0.1.43
type TokenRotation struct {
// contains filtered or unexported fields
}
func NewTokenRotation ¶ added in v0.1.43
func NewTokenRotation(config RotationConfig) *TokenRotation
func (*TokenRotation) GetRefreshCount ¶ added in v0.1.43
func (r *TokenRotation) GetRefreshCount(tokenID string) int
func (*TokenRotation) RecordRefresh ¶ added in v0.1.43
func (r *TokenRotation) RecordRefresh(tokenID string)
func (*TokenRotation) ResetRotation ¶ added in v0.1.43
func (r *TokenRotation) ResetRotation(tokenID string)
func (*TokenRotation) ShouldRotate ¶ added in v0.1.43
func (r *TokenRotation) ShouldRotate(tokenID string) bool