Documentation
¶
Overview ¶
Package jwt provides JWT creation, signing, decoding, and validation helpers for the security module.
It supports multiple signing strategies, including HMAC, RSA, RSA-PSS, and Ed25519, and lets applications attach custom validation callbacks after the token signature has been verified.
Main entry points:
- New to build a Service from explicit options
- NewConfiguredService to build a Service from viper-backed configuration
- Encode to create a signed token from claims
- Decode to validate a token and unmarshal claims into a destination value
The package is transport-agnostic and can be used directly by HTTP handlers, gRPC services, or higher-level authentication middleware.
Index ¶
- Constants
- Variables
- func SetJWTAsymmetricKeys(priv, pub, alg string) error
- type ConfigServiceInput
- type Ed25519ServiceInput
- type HMACServiceInput
- type Header
- type Option
- func WithContextTimeout(timeout time.Duration) Option
- func WithCustomStrategy(algorithm string, sign SignFunc, verify VerifyFunc) Option
- func WithEd25519(privateKey ed25519.PrivateKey, publicKey ed25519.PublicKey) Option
- func WithHMACSHA256(secret string) Option
- func WithRSAPSSSHA256(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Option
- func WithRSASHA256(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Option
- func WithStrategy(strategy Strategy) Option
- func WithValidator(validator Validator) Option
- type RSAServiceInput
- type Service
- func New(options ...Option) (*Service, error)
- func NewConfiguredService(input ConfigServiceInput) (*Service, error)
- func NewEd25519Service(input Ed25519ServiceInput) (*Service, error)
- func NewHMACService(input HMACServiceInput) (*Service, error)
- func NewRSAPSSService(input RSAServiceInput) (*Service, error)
- func NewRSAService(input RSAServiceInput) (*Service, error)
- func (service *Service) Create(claims any) (string, error)
- func (service *Service) CreateWithContext(ctx context.Context, claims any) (string, error)
- func (service *Service) Decode(ctx context.Context, token string, destination any, validators ...Validator) (*Token, error)
- func (service *Service) Read(token string, destination any) error
- func (service *Service) ReadWithContext(ctx context.Context, token string, destination any) error
- func (service *Service) ValidateSignature(token string) error
- func (service *Service) ValidateSignatureWithContext(ctx context.Context, token string) error
- type SignFunc
- type Strategy
- func NewCustomStrategy(algorithm string, sign SignFunc, verify VerifyFunc) (Strategy, error)
- func NewEd25519(privateKey ed25519.PrivateKey, publicKey ed25519.PublicKey) Strategy
- func NewHMACSHA256(secret string) Strategy
- func NewRSAPSSSHA256(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Strategy
- func NewRSASHA256(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Strategy
- type Token
- type Validator
- type VerifyFunc
Constants ¶
const ( DefaultAlgorithmKey = "jwt.algorithm" DefaultHMACSecretKey = "jwt.hmac.secret" DefaultRSAPrivateKeyKey = "jwt.rsa.private_key" DefaultRSAPublicKeyKey = "jwt.rsa.public_key" DefaultEdDSAPrivateKeyKey = "jwt.eddsa.private_key" DefaultEdDSAPublicKeyKey = "jwt.eddsa.public_key" )
Variables ¶
var ( ErrNilStrategy = errors.New("jwt: signing strategy is required") ErrMissingSecret = errors.New("jwt: secret is required") ErrMissingPrivateKey = errors.New("jwt: private key is required") ErrMissingPublicKey = errors.New("jwt: public key is required") ErrMissingEdDSAPrivateKey = errors.New("jwt: ed25519 private key is required") ErrMissingEdDSAPublicKey = errors.New("jwt: ed25519 public key is required") ErrInvalidToken = errors.New("jwt: invalid token format") ErrInvalidSignature = errors.New("jwt: invalid token signature") ErrUnexpectedAlg = errors.New("jwt: unexpected algorithm") ErrNilDestination = errors.New("jwt: destination is required") ErrNilValidator = errors.New("jwt: validator cannot be nil") ErrMissingValidation = errors.New("jwt: validation callback is required") ErrUnsupportedAlg = errors.New("jwt: unsupported algorithm") ErrMissingAlgorithm = errors.New("jwt: algorithm is required") ErrMissingSignFunc = errors.New("jwt: custom sign function is required") ErrMissingVerifyFunc = errors.New("jwt: custom verify function is required") )
Functions ¶
func SetJWTAsymmetricKeys ¶
SetJWTAsymmetricKeys stores the configured asymmetric key pair in viper using the standard JWT config keys for the selected algorithm. Existing values are overwritten with Set, while previously unset values are registered with SetDefault so package defaults remain discoverable. Supported algorithms are "rsa" and "eddsa", matched case-insensitively.
Types ¶
type ConfigServiceInput ¶
type ConfigServiceInput struct {
// Algorithm selects the signing strategy; when empty it is read from viper.
Algorithm string
// HMACSecretKey is the viper key used to read the HS256 shared key.
HMACSecretKey *string
// RSAPrivateKeyKey is the viper key used to read the RSA private key.
RSAPrivateKeyKey *string
// RSAPublicKeyKey is the viper key used to read the RSA public key.
RSAPublicKeyKey *string
// EdDSAPrivateKeyKey is the viper key used to read the Ed25519 private key.
EdDSAPrivateKeyKey *string
// EdDSAPublicKeyKey is the viper key used to read the Ed25519 public key.
EdDSAPublicKeyKey *string
// Validator optionally adds a post-signature validation callback.
Validator Validator
// contains filtered or unexported fields
}
ConfigServiceInput configures NewConfiguredService. When Algorithm is empty, the constructor reads it from viper. Validator is optional.
type Ed25519ServiceInput ¶
type Ed25519ServiceInput struct {
// PrivateKey signs EdDSA tokens when provided.
PrivateKey ed25519.PrivateKey
// PublicKey verifies EdDSA token signatures when provided.
PublicKey ed25519.PublicKey
// PrivateKeyEnv is the viper key used to read the private key when PrivateKey is nil.
PrivateKeyEnv string
// PublicKeyEnv is the viper key used to read the public key when PublicKey is nil.
PublicKeyEnv string
// Validator optionally adds a post-signature validation callback.
Validator Validator
}
Ed25519ServiceInput configures NewEd25519Service.
type HMACServiceInput ¶
type HMACServiceInput struct {
// Secret is the HS256 shared key used directly when provided.
Secret string
// SecretEnv is the viper key used to read the shared key when Secret is empty.
SecretEnv string
// Validator optionally adds a post-signature validation callback.
Validator Validator
}
HMACServiceInput configures NewHMACService. SecretEnv keeps its original name for compatibility and is treated as a viper key when Secret is empty. Validator is optional.
type Header ¶
type Header struct {
// Type identifies the token type, usually "JWT".
Type string `json:"typ"`
// Algorithm identifies the signing algorithm used by the token.
Algorithm string `json:"alg"`
}
Header represents the standard JWT header section.
type Option ¶
Option configures a Service instance during construction.
func WithContextTimeout ¶
WithContextTimeout configures a maximum duration for JWT signing, signature verification, and validation work performed by the service.
func WithCustomStrategy ¶
func WithCustomStrategy(algorithm string, sign SignFunc, verify VerifyFunc) Option
WithCustomStrategy configures the service to sign and verify tokens with caller-provided functions.
func WithEd25519 ¶
func WithEd25519(privateKey ed25519.PrivateKey, publicKey ed25519.PublicKey) Option
WithEd25519 configures the service to use Ed25519 signatures.
func WithHMACSHA256 ¶
WithHMACSHA256 configures the service to use HMAC-SHA256 signatures.
func WithRSAPSSSHA256 ¶
func WithRSAPSSSHA256(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Option
WithRSAPSSSHA256 configures the service to use RSA-PSS SHA-256 signatures.
func WithRSASHA256 ¶
func WithRSASHA256(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Option
WithRSASHA256 configures the service to use RSA-SHA256 signatures.
func WithStrategy ¶
WithStrategy injects a custom signing strategy into the service.
func WithValidator ¶
WithValidator registers a validator that will run on every Decode call after signature verification and claim decoding succeed.
type RSAServiceInput ¶
type RSAServiceInput struct {
// PrivateKey signs RS256 tokens when provided.
PrivateKey *rsa.PrivateKey
// PublicKey verifies RS256 token signatures when provided.
PublicKey *rsa.PublicKey
// PrivateKeyEnv is the viper key used to read the private key when PrivateKey is nil.
PrivateKeyEnv string
// PublicKeyEnv is the viper key used to read the public key when PublicKey is nil.
PublicKeyEnv string
// Validator optionally adds a post-signature validation callback.
Validator Validator
}
RSAServiceInput configures NewRSAService. PrivateKeyEnv and PublicKeyEnv keep their original names for compatibility and are treated as viper keys when the corresponding key is nil. Validator is optional.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is a facade over JWT creation and validation. It uses a Strategy for cryptographic concerns and a validation pipeline for domain-specific checks.
func New ¶
New builds a JWT service from the provided options. A signing strategy must be configured, either directly with WithStrategy or through a convenience option such as WithHMACSHA256.
func NewConfiguredService ¶
func NewConfiguredService(input ConfigServiceInput) (*Service, error)
NewConfiguredService builds a JWT service based on the configured algorithm. It reads values from viper using the provided keys or the package defaults.
func NewEd25519Service ¶
func NewEd25519Service(input Ed25519ServiceInput) (*Service, error)
NewEd25519Service builds a JWT service for EdDSA signatures.
func NewHMACService ¶
func NewHMACService(input HMACServiceInput) (*Service, error)
NewHMACService builds a JWT service for HS256 signatures. The secret can be provided directly or loaded from viper.
func NewRSAPSSService ¶
func NewRSAPSSService(input RSAServiceInput) (*Service, error)
NewRSAPSSService builds a JWT service for PS256 signatures.
func NewRSAService ¶
func NewRSAService(input RSAServiceInput) (*Service, error)
NewRSAService builds a JWT service for RS256 signatures. Keys can be provided directly or loaded from viper values. Configured values may point to PEM files containing PKCS#8 private and X.509 public keys, or keep the previous Base64-encoded DER format for compatibility.
func (*Service) Create ¶
Create builds and signs a JWT using the configured signing strategy. The token header is generated automatically, so callers only provide claims.
func (*Service) CreateWithContext ¶
CreateWithContext builds and signs a JWT using ctx plus any service timeout.
func (*Service) Decode ¶
func (service *Service) Decode(ctx context.Context, token string, destination any, validators ...Validator) (*Token, error)
Decode validates the token signature, unmarshals its claims into destination, and runs both service-level and per-call validators.
func (*Service) Read ¶
Read validates the token and unmarshals its claims into destination using a background context and the service-level validators.
func (*Service) ReadWithContext ¶
ReadWithContext validates the token and unmarshals its claims into destination using ctx plus any service timeout.
func (*Service) ValidateSignature ¶
ValidateSignature verifies the JWT structure, algorithm, and signature without decoding its claims into a destination value.
type Strategy ¶
type Strategy interface {
Algorithm() string
Sign(signingInput []byte) ([]byte, error)
Verify(signingInput []byte, signature []byte) error
}
Strategy defines how a JWT is signed and how its signature is verified. Different algorithms can be supported by providing alternative implementations.
func NewCustomStrategy ¶
func NewCustomStrategy(algorithm string, sign SignFunc, verify VerifyFunc) (Strategy, error)
NewCustomStrategy returns a signing strategy backed by caller-provided signing and verification functions.
func NewEd25519 ¶
func NewEd25519(privateKey ed25519.PrivateKey, publicKey ed25519.PublicKey) Strategy
NewEd25519 returns an Ed25519 signing strategy.
func NewHMACSHA256 ¶
NewHMACSHA256 returns an HMAC-SHA256 signing strategy.
func NewRSAPSSSHA256 ¶
func NewRSAPSSSHA256(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Strategy
NewRSAPSSSHA256 returns an RSA-PSS SHA-256 signing strategy.
func NewRSASHA256 ¶
func NewRSASHA256(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey) Strategy
NewRSASHA256 returns an RSA-SHA256 signing strategy. The private key is used to sign tokens and the public key is used to verify them.
type Token ¶
type Token struct {
// Raw is the original compact JWT string.
Raw string
// Header contains the decoded JWT header.
Header Header
// Claims contains the decoded JWT claims payload.
Claims json.RawMessage
// Signature is the encoded JWT signature segment.
Signature string
}
Token contains the parsed pieces of a validated JWT.