Overview
Thebearerauth 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
- Token Extraction: The middleware reads the configured header (default: “Authorization”) and extracts the token after the auth scheme prefix (default: “Bearer ”).
-
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
ValidatororValidatorWithContextto validate the token - Stores the token or claims in the request context using a private context key
-
Context Storage: The middleware uses a private
contextKeystruct to store authentication data in the request context. This prevents key collisions with other middleware or application code. -
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 (typeany)Token(c): Returns token string (only when usingValidator)Claims[T](c): Type-safe claims extraction (when usingValidatorWithContext)
Security Considerations
- Token Security - Use cryptographically secure tokens
- HTTPS Required - Always use HTTPS to protect tokens in transit
- Token Expiration - Implement token expiration
- Secure Storage - Store tokens securely on the client
- 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