Documentation
¶
Overview ¶
Package jwt provides a generic JWT token service using Go generics.
The service is parameterized by a custom claims type T, which must implement jwt.Claims (typically by embedding jwt.RegisteredClaims). This allows each project to define its own claims structure without gokit knowing about it.
Usage:
type MyClaims struct {
jwt.RegisteredClaims
UserID string `json:"user_id"`
TenantID string `json:"tenant_id"`
}
svc, err := jwt.NewService(cfg, func() *MyClaims { return &MyClaims{} })
token, err := svc.Generate(&MyClaims{
RegisteredClaims: jwt.RegisteredClaims{Subject: "user-123"},
UserID: "user-123",
})
claims, err := svc.Parse(tokenString)
Index ¶
- type Config
- type Service
- func (s *Service[T]) Generate(claims T) (string, error)
- func (s *Service[T]) GenerateAccess(claims T) (string, error)
- func (s *Service[T]) GenerateRefresh(claims T) (string, error)
- func (s *Service[T]) Parse(tokenString string) (T, error)
- func (s *Service[T]) ValidatorFunc() func(string) (any, error)
- type SigningMethod
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Secret is the HMAC signing key (required for HS* methods).
Secret string `mapstructure:"secret"`
// RefreshSecret is an optional separate secret for refresh tokens.
// If empty, Secret is used for both access and refresh tokens.
RefreshSecret string `mapstructure:"refresh_secret"`
// PrivateKeyPath is the path to an RSA or ECDSA private key PEM file.
// Used for RS*/ES* methods. Alternative to Secret for asymmetric signing.
PrivateKeyPath string `mapstructure:"private_key_path"`
// PublicKeyPath is the path to the corresponding public key PEM file.
// If empty, the public key is derived from the private key.
PublicKeyPath string `mapstructure:"public_key_path"`
// Method is the signing algorithm (default: "HS256").
Method SigningMethod `mapstructure:"method"`
// Issuer is the "iss" claim value (optional).
Issuer string `mapstructure:"issuer"`
// Audience is the "aud" claim value (optional).
Audience []string `mapstructure:"audience"`
// AccessTokenTTL is the lifetime of access tokens (default: "15m").
AccessTokenTTL time.Duration `mapstructure:"access_token_ttl"`
// RefreshTokenTTL is the lifetime of refresh tokens (default: "168h" / 7 days).
RefreshTokenTTL time.Duration `mapstructure:"refresh_token_ttl"`
// PrivateKey is the parsed RSA or ECDSA private key (set programmatically).
PrivateKey interface{} `mapstructure:"-"`
// PublicKey is the parsed RSA or ECDSA public key (set programmatically).
PublicKey interface{} `mapstructure:"-"`
}
Config configures the JWT token service. Loadable from YAML/env via mapstructure tags.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults sets sensible defaults for zero-valued fields.
type Service ¶
Service provides JWT token generation and parsing for custom claims type T. T must implement jwt.Claims (e.g., by embedding jwt.RegisteredClaims).
func NewService ¶
NewService creates a new JWT service. The newEmpty function returns a zero-value instance of T for parsing.
Example:
svc, err := jwt.NewService(cfg, func() *MyClaims { return &MyClaims{} })
func (*Service[T]) Generate ¶
Generate creates a signed JWT token from the given claims. If RegisteredClaims.ExpiresAt is zero, it is set to now + AccessTokenTTL. If RegisteredClaims.IssuedAt is zero, it is set to now.
func (*Service[T]) GenerateAccess ¶
GenerateAccess creates a signed access token with standard time claims. It calls prepareClaims with AccessTokenTTL before signing.
func (*Service[T]) GenerateRefresh ¶
GenerateRefresh creates a signed refresh token with standard time claims. It calls prepareClaims with RefreshTokenTTL before signing.
func (*Service[T]) Parse ¶
Parse validates and parses a JWT token string into claims of type T. It verifies the signature, expiry, and optionally issuer/audience.
func (*Service[T]) ValidatorFunc ¶
ValidatorFunc returns a function that validates a token string and returns the parsed claims as any. This bridges the typed JWT service with generic middleware that doesn't know about the specific claims type.
To get an auth.TokenValidator interface, wrap with auth.TokenValidatorFunc:
validator := auth.TokenValidatorFunc(svc.ValidatorFunc())
Or use the convenience helper:
validator := auth.NewJWTValidator(svc)
type SigningMethod ¶
type SigningMethod string
SigningMethod defines supported JWT signing algorithms.
const ( HS256 SigningMethod = "HS256" HS384 SigningMethod = "HS384" HS512 SigningMethod = "HS512" RS256 SigningMethod = "RS256" RS384 SigningMethod = "RS384" RS512 SigningMethod = "RS512" ES256 SigningMethod = "ES256" ES384 SigningMethod = "ES384" ES512 SigningMethod = "ES512" )