jwt

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2025 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeMissingToken        = "MISSING_TOKEN"
	CodeInvalidToken        = "INVALID_TOKEN"
	CodeInvalidClaims       = "INVALID_CLAIMS"
	CodeAuthorizationFailed = "AUTHORIZATION_FAILED"
	CodeJWKSUnavailable     = "JWKS_UNAVAILABLE"
	CodeKeyNotFound         = "KEY_NOT_FOUND"
)

JWT-specific error codes

Variables

View Source
var (
	ErrMissingToken        = errors.New("missing or invalid authentication token")
	ErrInvalidToken        = errors.New("invalid or expired token")
	ErrInvalidClaims       = errors.New("token claims validation failed")
	ErrAuthorizationFailed = errors.New("authorization failed")
	ErrJWKSUnavailable     = errors.New("JWKS endpoint unavailable")
	ErrKeyNotFound         = errors.New("token signing key not available")
)

JWT-specific authentication errors

Functions

func GetClaimValue

func GetClaimValue(r *http.Request, key string) (interface{}, bool)

GetClaimValue retrieves a specific claim value from the request context

func GetClaims

func GetClaims(r *http.Request) (jwt.MapClaims, bool)

GetClaims retrieves the JWT claims from the request context

func GetSubject

func GetSubject(r *http.Request) (string, bool)

GetSubject retrieves the subject (sub) claim from the request context

func GetToken

func GetToken(r *http.Request) (string, bool)

GetToken retrieves the raw JWT token string from the request context

func Middleware

func Middleware(config Config) func(http.Handler) http.Handler

Middleware creates a new JWT authentication middleware with the given configuration

Types

type Config

type Config struct {
	// Disabled disables JWT authentication when set to true
	// When disabled, the middleware will pass through all requests without authentication
	// This is useful for local development or testing environments
	// Default: false
	Disabled bool

	// JWKSURL is the URL to fetch the JSON Web Key Set for token validation
	// This is the primary method for key management in production environments
	JWKSURL string

	// JWKSRefreshInterval defines how often to refresh the JWKS from the URL
	// Default: 1 hour
	JWKSRefreshInterval time.Duration

	// SigningKey is an alternative to JWKS for simpler scenarios
	// For HMAC algorithms (HS256, HS384, HS512), this should be a []byte
	// For RSA algorithms (RS256, RS384, RS512), this should be a *rsa.PublicKey
	// Note: If JWKSURL is provided, this field is ignored
	SigningKey interface{}

	// TokenLookup defines where to extract the JWT token from the request
	// Format: "<source>:<name>"
	// Possible values:
	// - "header:<name>" - extract from HTTP header (e.g., "header:Authorization")
	//   When using "header:Authorization", the Bearer scheme is automatically handled
	// - "query:<name>" - extract from query parameter (e.g., "query:token")
	// - "cookie:<name>" - extract from cookie (e.g., "cookie:jwt")
	// Default: "header:Authorization"
	TokenLookup string

	// SuccessHandler is an optional handler called after successful token validation
	// Can be used for additional validation, logging, etc.
	SuccessHandler func(w http.ResponseWriter, r *http.Request, claims jwt.MapClaims) error

	// Logger is an optional slog logger for logging authentication events
	Logger *slog.Logger

	// ValidateIssuer enables issuer validation
	// If set, the token's "iss" claim must match this value
	ValidateIssuer string

	// ValidateAudience enables audience validation (optional)
	// If set, the token's "aud" claim must contain this value
	// If empty, audience validation is skipped
	ValidateAudience string

	// SignatureAlgorithm specifies the expected signature algorithm (optional)
	// Common values: RS256, RS384, RS512, HS256, HS384, HS512, ES256, ES384, ES512
	// If set, incoming tokens must use this algorithm
	// If empty, algorithm validation is skipped (except JWK alg validation if present)
	SignatureAlgorithm string

	// ClockSkew allows for clock skew when validating time-based claims
	// Default: 0 (no skew tolerance)
	ClockSkew time.Duration

	// HTTPClient is the HTTP client used to fetch JWKS
	// If not set, http.DefaultClient is used
	HTTPClient *http.Client
}

Config holds the configuration for JWT authentication middleware

type JWK

type JWK struct {
	Kid string   `json:"kid"`
	Kty string   `json:"kty"`
	Use string   `json:"use"`
	N   string   `json:"n"`
	E   string   `json:"e"`
	Alg string   `json:"alg"`
	X5c []string `json:"x5c,omitempty"`
}

JWK represents a JSON Web Key

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

JWKS represents a JSON Web Key Set

Jump to

Keyboard shortcuts

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