Documentation
¶
Overview ¶
Package jwtutil provides a reusable, library-friendly JWT authentication layer built on top of the `common/crypto` JWT primitives.
It adds the pieces needed for real-world auth flows that the low-level crypto.JWT type does not cover:
- Token pairs: short-lived access token + long-lived refresh token.
- Refresh flow: issue a new access token from a valid refresh token.
- Revocation / blacklist: pluggable TokenStore for invalidating tokens before their natural expiry (logout, password change, etc.).
- Claims builder: fluent API for constructing common claim sets.
- HTTP helpers: extract bearer tokens, context-based claim retrieval, and a generic auth middleware wrapper.
Quick start ¶
auth, err := jwtutil.New(jwtutil.Config{
Secret: []byte("my-32-byte-secret-1234567890123456"),
Issuer: "my-app",
AccessTTL: 15 * time.Minute,
RefreshTTL: 7 * 24 * time.Hour,
})
if err != nil {
log.Fatal(err)
}
// Issue a token pair at login.
pair, err := auth.Login("user-123", jwtutil.Roles("admin"))
// pair.AccessToken, pair.RefreshToken
// Verify an access token (from Authorization: Bearer <token>).
claims, err := auth.Verify(pair.AccessToken)
// Refresh.
pair, err = auth.Refresh(pair.RefreshToken)
// Revoke (logout).
auth.Revoke(context.Background(), pair.AccessToken)
Index ¶
- Variables
- func ContextWithClaims(ctx context.Context, claims *Claims) context.Context
- func ExtractBearer(authHeader string) (string, error)
- type Auth
- func (a *Auth) IssueAccess(subject string, opts ...IssueOption) (string, error)
- func (a *Auth) Login(subject string, opts ...IssueOption) (*TokenPair, error)
- func (a *Auth) Refresh(refreshToken string) (*TokenPair, error)
- func (a *Auth) Revoke(ctx context.Context, accessToken string) error
- func (a *Auth) RevokeRefresh(ctx context.Context, refreshToken string) error
- func (a *Auth) SetIDGenerator(g IDGenerator)
- func (a *Auth) SetStore(s TokenStore)
- func (a *Auth) Verify(token string) (*Claims, error)
- func (a *Auth) VerifyRefresh(token string) (*Claims, error)
- type Claims
- type Config
- type CounterIDGenerator
- type IDGenerator
- type IssueOption
- type MemoryTokenStore
- func (s *MemoryTokenStore) Cleanup()
- func (s *MemoryTokenStore) IsRevoked(_ context.Context, jti string) (bool, error)
- func (s *MemoryTokenStore) Len() (revoked, used int)
- func (s *MemoryTokenStore) MarkUsed(_ context.Context, jti string, expiry time.Time) (bool, error)
- func (s *MemoryTokenStore) Revoke(_ context.Context, jti string, expiry time.Time) error
- type TokenPair
- type TokenStore
- type TokenType
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidToken is returned when a token is malformed or has an invalid signature. ErrInvalidToken = errors.New("jwtutil: invalid token") // ErrTokenExpired is returned when a token has passed its expiry time. ErrTokenExpired = errors.New("jwtutil: token expired") // ErrTokenNotYetValid is returned when a token's nbf claim is in the future. ErrTokenNotYetValid = errors.New("jwtutil: token not yet valid") // ErrTokenRevoked is returned when a token has been revoked via the TokenStore. ErrTokenRevoked = errors.New("jwtutil: token revoked") // ErrWrongTokenType is returned when a refresh token is used where an access // token is expected, or vice versa. ErrWrongTokenType = errors.New("jwtutil: wrong token type") )
Functions ¶
func ContextWithClaims ¶
ContextWithClaims stores claims in a context.
func ExtractBearer ¶
ExtractBearer extracts the token from an "Authorization: Bearer <token>" header value. Returns the token and nil if successful.
Types ¶
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth is the JWT authentication manager. It signs, verifies, refreshes, and revokes tokens.
func (*Auth) IssueAccess ¶
func (a *Auth) IssueAccess(subject string, opts ...IssueOption) (string, error)
IssueAccess issues a standalone access token (without a refresh token).
func (*Auth) Login ¶
func (a *Auth) Login(subject string, opts ...IssueOption) (*TokenPair, error)
Login issues a token pair (access + refresh) for the given subject. Additional claims can be set via options.
func (*Auth) Refresh ¶
Refresh validates a refresh token and issues a new token pair. If the TokenStore supports MarkUsed, the old refresh token is marked as used to prevent replay attacks.
func (*Auth) RevokeRefresh ¶
RevokeRefresh marks a refresh token as revoked. Requires a TokenStore.
func (*Auth) SetIDGenerator ¶
func (a *Auth) SetIDGenerator(g IDGenerator)
SetIDGenerator overrides the default jti generator.
func (*Auth) SetStore ¶
func (a *Auth) SetStore(s TokenStore)
SetStore overrides the token store (can also be set via Config.Store).
type Claims ¶
type Claims struct {
// Standard JWT claims.
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audience string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
ID string `json:"jti,omitempty"`
// Auth-specific claims.
TokenType TokenType `json:"type,omitempty"`
Roles []string `json:"roles,omitempty"`
Permissions []string `json:"perms,omitempty"`
// Extra holds any additional non-standard claims.
Extra map[string]any `json:"-"`
}
Claims represents the decoded JWT claims with auth-specific fields.
func ClaimsFromContext ¶
ClaimsFromContext retrieves claims from a context, or nil if not present.
func (*Claims) HasPermission ¶
HasPermission returns true if the claims include the given permission.
type Config ¶
type Config struct {
// Secret is the HMAC secret key (for HS256/HS512). Required if using HMAC.
Secret []byte
// Algorithm is the signing algorithm. Default: HS256.
Algorithm crypto.JWTAlgorithm
// RSAPriv is the RSA private key for RS256 signing. Required if using RS256.
RSAPriv *rsa.PrivateKey
// RSAPub is the RSA public key for RS256 verification. Required if using RS256.
RSAPub *rsa.PublicKey
// Issuer is the iss claim. Optional.
Issuer string
// Audience is the aud claim. Optional.
Audience string
// AccessTTL is the access token lifetime. Default: 15m.
AccessTTL time.Duration
// RefreshTTL is the refresh token lifetime. Default: 168h (7 days).
RefreshTTL time.Duration
// Store is the optional token revocation store. If nil, revocation is
// not enforced (tokens remain valid until expiry).
Store TokenStore
// Leeway is the clock skew tolerance for exp/nbf checks. Default: 0.
Leeway time.Duration
}
Config configures the JWT auth manager.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
type CounterIDGenerator ¶
type CounterIDGenerator struct {
// contains filtered or unexported fields
}
CounterIDGenerator is a deterministic, monotonic ID generator for testing.
func NewCounterIDGenerator ¶
func NewCounterIDGenerator() *CounterIDGenerator
NewCounterIDGenerator creates a counter-based ID generator starting at 1.
func (*CounterIDGenerator) NewID ¶
func (g *CounterIDGenerator) NewID() (string, error)
type IDGenerator ¶
IDGenerator generates unique token IDs (jti claim).
type IssueOption ¶
type IssueOption func(*Claims)
IssueOption modifies the claims during token issuance.
func WithAudience ¶
func WithAudience(aud string) IssueOption
WithAudience overrides the audience claim for this token.
func WithExtra ¶
func WithExtra(key string, value any) IssueOption
WithExtra sets an extra claim key-value pair.
func WithPermissions ¶
func WithPermissions(perms ...string) IssueOption
WithPermissions sets the permissions claim.
type MemoryTokenStore ¶
type MemoryTokenStore struct {
// contains filtered or unexported fields
}
MemoryTokenStore is an in-process TokenStore. Useful for single-instance deployments and testing. Not suitable for multi-instance setups.
func NewMemoryTokenStore ¶
func NewMemoryTokenStore() *MemoryTokenStore
NewMemoryTokenStore creates an in-memory token store.
func (*MemoryTokenStore) Cleanup ¶
func (s *MemoryTokenStore) Cleanup()
Cleanup removes expired entries from the store. This should be called periodically to prevent unbounded memory growth.
func (*MemoryTokenStore) IsRevoked ¶
IsRevoked returns true if the token ID has been revoked and its revocation expiry has not passed.
func (*MemoryTokenStore) Len ¶
func (s *MemoryTokenStore) Len() (revoked, used int)
Len returns the number of revoked and used entries.
type TokenPair ¶
type TokenPair struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int64 `json:"expires_in"` // access token TTL in seconds
TokenType string `json:"token_type"` // always "Bearer"
}
TokenPair holds an access token and its associated refresh token.
type TokenStore ¶
type TokenStore interface {
// Revoke marks the token ID (jti) as revoked until the given expiry.
Revoke(ctx context.Context, jti string, expiry time.Time) error
// IsRevoked returns true if the token ID has been revoked.
IsRevoked(ctx context.Context, jti string) (bool, error)
// MarkUsed marks a refresh token ID as used (for one-time refresh tokens).
// Returns true if it was not previously used, false if already used.
MarkUsed(ctx context.Context, jti string, expiry time.Time) (bool, error)
}
TokenStore is a pluggable store for tracking revoked tokens. Implementations can be in-memory (for single-instance), Redis, etc.
A token is considered revoked if IsRevoked returns true for its jti. The store is also used to track refresh tokens that have been used (to prevent replay attacks).