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
| Option | Type | Default | Description |
|---|---|---|---|
Realm | string | "Restricted" | Authentication realm shown in browser prompt |
Validator | ValidatorFunc | - | Custom function to validate credentials |
ErrorHandler | func(*mizu.Ctx) error | - | Custom handler for auth failures |
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:| Test Case | Description | Expected Behavior |
|---|---|---|
| TestNew/allows valid credentials | Valid username and password provided | Returns 200 OK and allows request through |
| TestNew/rejects invalid password | Valid username with incorrect password | Returns 401 Unauthorized |
| TestNew/rejects unknown user | Non-existent username provided | Returns 401 Unauthorized |
| TestNew/rejects missing auth | No Authorization header present | Returns 401 Unauthorized with WWW-Authenticate header |
| TestWithValidator | Custom validator function with valid credentials | Returns 200 OK when validator returns true |
| TestWithRealm | Custom realm configuration | Returns 401 with WWW-Authenticate header containing custom realm |
| TestWithOptions_ErrorHandler | Custom error handler on auth failure | Calls custom error handler returning JSON response |
| TestWithOptions_InvalidAuth/not basic | Authorization header with Bearer scheme | Returns 401 Unauthorized |
| TestWithOptions_InvalidAuth/invalid base64 | Malformed base64 in Authorization header | Returns 401 Unauthorized |
| TestWithOptions_InvalidAuth/no colon | Base64 credentials without colon separator | Returns 401 Unauthorized |
| TestWithOptions_Panics | Creating middleware without validator | Panics with error message |
| TestSecureCompare/password_password | Comparing identical strings | Returns true |
| TestSecureCompare/password_different | Comparing different strings | Returns false |
| TestSecureCompare/short_longpassword | Comparing strings of different lengths | Returns false |
| TestSecureCompare/empty_empty | Comparing empty strings | Returns true |
Related Middlewares
- bearerauth - Token-based authentication
- keyauth - API key authentication
- secure - HTTPS enforcement
- ratelimit - Rate limiting