ntex-basicauth
A Basic Authentication middleware designed for the ntex web framework.
Features
- Cache - Built-in authentication result cache to reduce validation overhead
- Flexible Configuration - Supports multiple user validation methods
- Path Filtering - Supports skipping authentication for specific paths
- BCrypt Support - Optional BCrypt password hashing (requires
bcryptfeature) - JSON Response - Optional JSON error response (requires
jsonfeature) - Custom Validator - Support for custom user validation logic
- Regex Paths - Regular expression path matching (requires
regexfeature)
Installation
Add the dependency in your Cargo.toml:
[]
= "^0"
[]
= { = "^0", = ["bcrypt"] }
Quick Start
Basic Usage
use web;
use BasicAuth;
use HashMap;
async
async
async
Using the Builder Pattern
use ;
use Duration;
let auth = new
.user
.user
.realm
.cache_ttl // 5 minutes cache
.cache_size_limit
.path_filter
.build
.unwrap;
new
.wrap
.service
BCrypt Password Support
After enabling the bcrypt feature:
use ;
let auth = new
.bcrypt_user // BCrypt hash
.bcrypt_user_with_password // Will hash automatically
.build
.unwrap;
Custom Validator
use ;
use Arc;
// Using custom validator
let auth = new
.validator
.build
.unwrap;
Getting User Information
Get authenticated user information in the request handler:
use web;
use ;
async
Configuration Options
BasicAuthConfig
let config = new
.realm // Set authentication realm
.disable_cache // Disable cache
.cache_size_limit // Set cache size limit
.path_filter; // Set path filter
PathFilter
let filter = new
.skip_exact // Skip exact path
.skip_prefix // Skip prefix match
.skip_suffix; // Skip suffix match
Error Handling
When authentication fails, the middleware returns HTTP 401 status code and corresponding error information:
Error types:
MissingHeader- Missing Authorization headerInvalidFormat- Invalid Authorization header formatInvalidBase64- Invalid Base64 encodingInvalidCredentials- Invalid user credentialsValidationFailed- User validation failed
Performance Optimization
Cache
Authentication cache is enabled by default, which can significantly reduce repeated validation overhead:
use Duration;
let auth = new
.users
.cache_ttl // 10 minutes
.cache_size_limit // Max 1000 entries
.cache_cleanup_interval // Cleanup every 5 min
.build
.unwrap;
License
This project is licensed under the MIT License.