Overview
Thebasicauth middleware provides HTTP Basic Authentication, a simple authentication scheme built into the HTTP protocol. It prompts users for a username and password, which are sent with each request.
Use it when you need:
- Simple password protection for admin areas
- Quick authentication for internal tools
- Development/staging environment protection
Installation
Quick Start
Configuration
Options
ValidatorFunc
Examples
Static Credentials
Custom Realm
Custom Validator
Validate against a database or external service:Custom Error Handler
Route-Specific Protection
Group Protection
API Reference
Functions
Types
Technical Details
The basicauth middleware implements HTTP Basic Authentication according to RFC 7617. Here are the key implementation details:Authentication Flow
- Header Extraction: Extracts the
Authorizationheader from the incoming request - Scheme Validation: Verifies the header starts with βBasic β prefix
- Base64 Decoding: Decodes the base64-encoded credentials using
base64.StdEncoding.DecodeString() - Credential Parsing: Splits the decoded string on the first colon (
:) to separate username and password - Validation: Calls the configured validator function to verify credentials
- Response: Either proceeds to the next handler or returns 401 Unauthorized with
WWW-Authenticateheader
Security Features
Constant-Time Comparison: The built-in validator usessecureCompare() function to prevent timing attacks:
- Hashes both strings using SHA-256 to normalize lengths
- Uses
crypto/subtle.ConstantTimeCompare()to prevent timing side-channels - Protects against timing attacks that could leak password information
WWW-Authenticate header with the configured realm, prompting the browser to display a login dialog.
Error Handling
The middleware returns 401 Unauthorized in these cases:- Missing
Authorizationheader - Invalid authorization scheme (not βBasicβ)
- Invalid base64 encoding
- Malformed credentials (no colon separator)
- Validator function returns false
Options.ErrorHandler to customize the response format (e.g., JSON instead of plain text).
Security Considerations
- Always use HTTPS - Basic auth sends credentials base64-encoded (not encrypted)
- Use strong passwords - Avoid dictionary words and short passwords
- Hash stored passwords - Never store plain-text passwords in your validator
- Consider rate limiting - Combine with
ratelimitto prevent brute force attacks - Timing attacks - The built-in validator uses constant-time comparison
Best Practices
- Use Basic Auth for simple internal tools, not production user-facing auth
- Combine with HTTPS redirect middleware
- Add rate limiting to prevent brute force attacks
- Use Bearer auth or session-based auth for APIs
Testing
The basicauth middleware includes comprehensive test coverage. Below are all test cases:Related Middlewares
- bearerauth - Token-based authentication
- keyauth - API key authentication
- secure - HTTPS enforcement
- ratelimit - Rate limiting