Documentation
¶
Overview ¶
Package jwt provides utilities for generating, parsing, and validating JSON Web Tokens (JWT) as well as HTTP middleware and context helpers for Go services.
The implementation focuses on the HS256 (HMAC-SHA256) algorithm. A high-level Service type wraps signing and verification while accepting any JSON- serialisable claims structure. StandardClaims is provided as a convenient struct mirroring the RFC 7519 registered fields.
Context helper functions make it easy to attach a token and its claims to a context.Context and retrieve them later in the request lifecycle.
Architecture ¶
- Service – signs and verifies tokens.
- context.go – helper functions for working with context.
- middleware.go – HTTP middleware that extracts a token (from header, cookie, query, or custom header) and injects verified claims into the request context.
- errors.go – sentinel error values returned by the package.
Usage ¶
import "github.com/dmitrymomot/saaskit/pkg/jwt"
// Initialise the service. svc, err := jwt.NewFromString("super-secret")
if err != nil {
// handle error
}
// Generate a token.
claims := jwt.StandardClaims{
Subject: "123",
ExpiresAt: time.Now().Add(24 * time.Hour).Unix(),
}
token, err := svc.Generate(claims)
// Parse the token back. var parsed jwt.StandardClaims
if err := svc.Parse(token, &parsed); err != nil {
// handle invalid / expired token
}
// Use middleware in an http.Handler chain. http.Handle("/api", jwt.Middleware(svc)(yourHandler))
Error Handling ¶
Errors such as ErrExpiredToken or ErrInvalidSignature are returned as sentinel variables and can be compared using errors.Is.
Performance Considerations ¶
The package uses only the Go standard library, avoiding external dependencies and allocations where possible. Signing keys are kept in memory only. No reflection is used during normal operation.
Index ¶
- Constants
- Variables
- func BearerTokenExtractor(r *http.Request) (string, error)
- func GetClaims[T any](ctx context.Context) (T, bool)
- func GetClaimsAs[T any](ctx context.Context, claims *T) error
- func GetToken(ctx context.Context) (string, bool)
- func Middleware(service *Service) func(next http.Handler) http.Handler
- func MiddlewareWithConfig(config MiddlewareConfig) func(next http.Handler) http.Handler
- func SetClaims(ctx context.Context, claims any) context.Context
- func SetToken(ctx context.Context, token string) context.Context
- type Header
- type MiddlewareConfig
- type Service
- type SkipFunc
- type StandardClaims
- type TokenExtractorFunc
Constants ¶
const ( HeaderType = "JWT" HeaderAlgorithm = "HS256" // HMAC-SHA256 chosen for security/performance balance )
JWT header constants required by RFC 7519
Variables ¶
var ( ErrInvalidToken = errors.New("jwt: invalid token") ErrExpiredToken = errors.New("jwt: token is expired") ErrInvalidSigningMethod = errors.New("jwt: invalid signing method") ErrMissingSigningKey = errors.New("jwt: missing signing key") ErrInvalidSigningKey = errors.New("jwt: invalid signing key") ErrInvalidClaims = errors.New("jwt: invalid claims") ErrMissingClaims = errors.New("jwt: missing claims") ErrInvalidSignature = errors.New("jwt: invalid signature") ErrUnexpectedSigningMethod = errors.New("jwt: unexpected signing method") )
Functions ¶
func BearerTokenExtractor ¶
BearerTokenExtractor extracts JWT tokens from "Authorization: Bearer <token>" headers. This is the most common JWT transport method per RFC 6750.
func GetClaims ¶
GetClaims retrieves JWT claims from context with type safety. Returns zero value and false if claims are missing or of wrong type.
func GetClaimsAs ¶
GetClaimsAs converts JWT claims from context to the specified type. Uses direct type assertion first, then JSON marshaling for type conversion. This flexibility supports both map[string]any and custom struct claims.
func Middleware ¶
Middleware creates JWT middleware with default Bearer token extraction. Validates tokens and injects claims into request context for downstream handlers.
func MiddlewareWithConfig ¶
func MiddlewareWithConfig(config MiddlewareConfig) func(next http.Handler) http.Handler
MiddlewareWithConfig creates JWT middleware with custom configuration.
Types ¶
type MiddlewareConfig ¶
type MiddlewareConfig struct {
Service *Service // JWT service for token validation
Extractor TokenExtractorFunc // Token extraction strategy (defaults to Bearer)
Skip SkipFunc // Optional request filter to bypass validation
}
MiddlewareConfig configures JWT middleware behavior.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service handles JWT token generation and validation using HMAC-SHA256. The signing key is kept in memory only and should be cryptographically secure.
func New ¶
New creates a new JWT service with the provided signing key. The key should be at least 32 bytes for adequate security with HMAC-SHA256.
func NewFromString ¶
NewFromString creates a new JWT service from a string signing key. Convenience wrapper around New() for string-based configuration.
type SkipFunc ¶
SkipFunc defines a function that determines whether to skip JWT validation for a request.
type StandardClaims ¶
type StandardClaims struct {
ID string `json:"jti,omitempty"` // JWT ID - unique identifier for preventing token reuse
Subject string `json:"sub,omitempty"` // Subject - typically user ID or entity identifier
Issuer string `json:"iss,omitempty"` // Issuer - identifies who issued the token
Audience string `json:"aud,omitempty"` // Audience - intended recipient(s) of the token
ExpiresAt int64 `json:"exp,omitempty"` // Expiration time - Unix timestamp when token expires
NotBefore int64 `json:"nbf,omitempty"` // Not before - Unix timestamp when token becomes valid
IssuedAt int64 `json:"iat,omitempty"` // Issued at - Unix timestamp when token was created
}
StandardClaims represents the registered JWT claims defined in RFC 7519 Section 4.1. All fields use Unix timestamps for temporal claims to ensure consistent validation.
func (StandardClaims) Valid ¶
func (c StandardClaims) Valid() error
Valid validates the temporal claims against current time. Zero values are treated as unset (per RFC 7519) and are ignored during validation.
type TokenExtractorFunc ¶
TokenExtractorFunc defines a function that extracts a token from an HTTP request.
func CookieTokenExtractor ¶
func CookieTokenExtractor(cookieName string) TokenExtractorFunc
CookieTokenExtractor creates a token extractor for cookie-based JWT transport. Useful for browser applications where Authorization headers aren't practical.
func HeaderTokenExtractor ¶
func HeaderTokenExtractor(headerName string) TokenExtractorFunc
HeaderTokenExtractor creates a token extractor for custom headers. Useful for APIs that use non-standard header names for token transport.
func QueryTokenExtractor ¶
func QueryTokenExtractor(paramName string) TokenExtractorFunc
QueryTokenExtractor creates a token extractor for URL query parameters. Generally discouraged due to token exposure in logs and referrer headers.