middleware

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 4 Imported by: 0

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClaimsFrom

func ClaimsFrom(ctx context.Context) *jwt.Claims

ClaimsFrom retrieves JWT claims from the request context. Returns nil when no authenticated claims are present.

func CustomClaimFrom

func CustomClaimFrom(ctx context.Context, key string) any

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

func JWT(svc *jwt.Service, opts ...MiddlewareOption) func(http.Handler) http.Handler

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

func Optional(svc *jwt.Service) func(http.Handler) http.Handler

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

func SubjectFrom(ctx context.Context) string

SubjectFrom returns the token subject (typically the user ID) from the context, or an empty string when no claims are present.

func WithClaims

func WithClaims(ctx context.Context, claims *jwt.Claims) context.Context

WithClaims stores JWT claims in the request context. This is called internally by the JWT middleware after successful token verification.

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.

Jump to

Keyboard shortcuts

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