Skip to main content

Overview

The bearerauth middleware validates Bearer tokens from the Authorization header. It’s commonly used for API authentication with JWTs, OAuth tokens, or custom tokens. Use it when you need:
  • API authentication with tokens
  • JWT validation
  • OAuth 2.0 Bearer token protection
  • Custom token authentication

Installation

Quick Start

Configuration

Options

Validator Types

Examples

Simple Token Validation

JWT Validation with Claims

Custom Header

Custom Auth Scheme

Custom Error Handler

Database Token Lookup

API Reference

Functions

Extracting Data

Error Types

Technical Details

Implementation Overview

The bearerauth middleware implements Bearer token authentication following RFC 6750 standards. It extracts and validates tokens from HTTP headers, storing the token or associated claims in the request context for downstream handlers.

Core Components

  1. Token Extraction: The middleware reads the configured header (default: “Authorization”) and extracts the token after the auth scheme prefix (default: “Bearer ”).
  2. Validation Flow:
    • Checks if the authorization header exists
    • Verifies the auth scheme matches the configured scheme
    • Extracts the token after removing the scheme prefix
    • Invokes either Validator or ValidatorWithContext to validate the token
    • Stores the token or claims in the request context using a private context key
  3. Context Storage: The middleware uses a private contextKey struct to store authentication data in the request context. This prevents key collisions with other middleware or application code.
  4. Error Handling: Three error types are defined:
    • ErrTokenMissing: Returned when no token is found (401 Unauthorized)
    • ErrInvalidScheme: Returned when auth scheme doesn’t match (403 Forbidden)
    • ErrTokenInvalid: Returned when validation fails (403 Forbidden)

Validator Types

  • TokenValidator: Simple boolean validation for basic token checking
  • TokenValidatorWithContext: Returns claims along with validation result, enabling stateful authentication with user data

Data Retrieval

Three helper functions extract authentication data from context:
  • FromContext(c): Returns raw token or claims (type any)
  • Token(c): Returns token string (only when using Validator)
  • Claims[T](c): Type-safe claims extraction (when using ValidatorWithContext)

Security Considerations

  1. Token Security - Use cryptographically secure tokens
  2. HTTPS Required - Always use HTTPS to protect tokens in transit
  3. Token Expiration - Implement token expiration
  4. Secure Storage - Store tokens securely on the client
  5. Revocation - Implement token revocation for logout/security

Best Practices

  • Use short-lived tokens with refresh tokens for better security
  • Validate token claims (expiration, issuer, audience)
  • Log authentication failures for security monitoring
  • Consider rate limiting failed attempts

Testing

The bearerauth middleware includes comprehensive test coverage for all authentication scenarios:
  • basicauth - Username/password authentication
  • keyauth - API key authentication
  • csrf - CSRF protection