jwt

package
v0.0.33 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 11, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

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

View Source
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

View Source
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

func SetJWTAsymmetricKeys(priv, pub, alg string) error

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 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

type Option func(*Service) error

Option configures a Service instance during construction.

func WithContextTimeout

func WithContextTimeout(timeout time.Duration) Option

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

func WithHMACSHA256(secret string) Option

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

func WithStrategy(strategy Strategy) Option

WithStrategy injects a custom signing strategy into the service.

func WithValidator

func WithValidator(validator Validator) Option

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

func New(options ...Option) (*Service, error)

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

func (service *Service) Create(claims any) (string, error)

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

func (service *Service) CreateWithContext(ctx context.Context, claims any) (string, error)

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

func (service *Service) Read(token string, destination any) error

Read validates the token and unmarshals its claims into destination using a background context and the service-level validators.

func (*Service) ReadWithContext

func (service *Service) ReadWithContext(ctx context.Context, token string, destination any) error

ReadWithContext validates the token and unmarshals its claims into destination using ctx plus any service timeout.

func (*Service) ValidateSignature

func (service *Service) ValidateSignature(token string) error

ValidateSignature verifies the JWT structure, algorithm, and signature without decoding its claims into a destination value.

func (*Service) ValidateSignatureWithContext

func (service *Service) ValidateSignatureWithContext(ctx context.Context, token string) error

ValidateSignatureWithContext verifies the JWT signature using ctx plus any service timeout.

type SignFunc

type SignFunc func(ctx context.Context, signingInput []byte) ([]byte, error)

SignFunc signs a JWT signing input and returns the raw signature bytes.

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

func NewHMACSHA256(secret string) Strategy

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.

type Validator

type Validator func(ctx context.Context, token Token) error

Validator represents an additional validation step executed after the token signature has been verified and its claims have been decoded.

type VerifyFunc

type VerifyFunc func(ctx context.Context, signingInput []byte, signature []byte) error

VerifyFunc validates raw signature bytes for a JWT signing input.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL