Skip to main content

Overview

The jwt middleware provides JSON Web Token (JWT) authentication. It validates tokens from the Authorization header and makes claims available to handlers. Use it when you need:
  • Stateless API authentication
  • Token-based user sessions
  • Microservices authentication

Installation

Quick Start

Configuration

Options

TokenLookup Formats

  • header:Authorization - From Authorization header
  • query:token - From query parameter
  • cookie:jwt - From cookie

Examples

Basic Usage

With Issuer Validation

Token from Query Parameter

Custom Error Handler

Accessing Claims

Protected Group

API Reference

Functions

Standard Claims

Technical Details

Token Validation Process

The JWT middleware implements a complete token validation workflow:
  1. Token Extraction: The middleware supports three token sources:
    • Header: Extracts from Authorization header with configurable scheme (default: “Bearer”)
    • Query: Extracts from URL query parameters
    • Cookie: Extracts from HTTP cookies
  2. Token Structure Validation: Validates the token has exactly three parts (header.payload.signature) separated by dots.
  3. Signature Verification: Uses HMAC-SHA256 to verify the token signature:
    • Decodes the signature from base64url encoding
    • Computes expected signature using the provided secret
    • Performs constant-time comparison to prevent timing attacks
  4. Payload Decoding: Decodes the base64url-encoded payload and unmarshals JSON claims.
  5. Claims Validation: Validates standard JWT claims:
    • exp (expiration): Rejects tokens past their expiration time
    • nbf (not before): Rejects tokens used before their valid time
    • iss (issuer): Validates against configured issuer if specified
    • aud (audience): Validates against configured audience list if specified (supports both string and array formats)

Context Storage

Claims are stored in the request context using a private context key. This prevents key collisions and ensures type safety. The GetClaims() and Subject() helper functions provide convenient access to the claims.

Error Handling

The middleware defines specific error types for different failure scenarios:
  • ErrTokenMissing: Returns 401 Unauthorized
  • ErrTokenMalformed, ErrTokenInvalid, ErrTokenExpired, ErrTokenNotYetValid, ErrInvalidScheme, ErrInvalidIssuer, ErrInvalidAudience: Return 403 Forbidden
Custom error handlers can be configured via the ErrorHandler option for application-specific error responses.

Security Considerations

  1. Use strong secrets - At least 32 bytes for HS256
  2. Always validate expiration - The middleware checks exp automatically
  3. Use HTTPS - Never transmit tokens over HTTP
  4. Short expiration times - Use refresh tokens for long sessions
  5. Validate issuer - Prevent tokens from other applications

Best Practices

  • Store secrets in environment variables
  • Use short-lived access tokens with refresh tokens
  • Include only necessary data in claims
  • Validate additional claims in handlers when needed

Testing

The JWT middleware includes comprehensive test coverage for all scenarios: