Documentation
¶
Overview ¶
Package middleware provides standard net/http middleware for JWT authentication. It is framework-agnostic and works with any router that accepts http.Handler.
Index ¶
- func ClaimsFrom(ctx context.Context) *jwt.Claims
- func CustomClaimFrom(ctx context.Context, key string) any
- func JWT(svc *jwt.Service, opts ...MiddlewareOption) func(http.Handler) http.Handler
- func Optional(svc *jwt.Service) func(http.Handler) http.Handler
- func RequireAuth(onError ...ErrorHandler) func(http.Handler) http.Handler
- func SubjectFrom(ctx context.Context) string
- func WithClaims(ctx context.Context, claims *jwt.Claims) context.Context
- type ErrorHandler
- type MiddlewareOption
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClaimsFrom ¶
ClaimsFrom retrieves JWT claims from the request context. Returns nil when no authenticated claims are present.
func CustomClaimFrom ¶
CustomClaimFrom retrieves a single custom claim value from the context by key. Returns nil when no claims are present or the key does not exist.
func JWT ¶
JWT returns an HTTP middleware that validates Bearer tokens in the Authorization header. On success, claims are stored in the request context and are accessible via ClaimsFrom / SubjectFrom.
Usage:
mux.Handle("/api/", middleware.JWT(jwtSvc)(apiHandler))
func Optional ¶
Optional is a variant of JWT that does not reject requests missing a token. When a valid token is present, claims are stored in the context as normal. When absent or invalid, the request passes through without claims.
Useful for endpoints that behave differently for authenticated and anonymous users.
func RequireAuth ¶
func RequireAuth(onError ...ErrorHandler) func(http.Handler) http.Handler
RequireAuth is a standalone middleware that rejects requests with no claims in the context. Pair it after Optional when you want a mixed auth chain.
func SubjectFrom ¶
SubjectFrom returns the token subject (typically the user ID) from the context, or an empty string when no claims are present.
Types ¶
type ErrorHandler ¶
type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
ErrorHandler is invoked when authentication fails. If not set, a default 401 JSON response is written.
type MiddlewareOption ¶
type MiddlewareOption func(*middlewareConfig)
MiddlewareOption configures JWT middleware behaviour.
func WithErrorHandler ¶
func WithErrorHandler(h ErrorHandler) MiddlewareOption
WithErrorHandler replaces the default 401 handler with a custom one.