ntex-basicauth
A Basic Authentication middleware 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 - BCrypt password hashing (enabled by default, disable with
default-features = false) - JSON Response - Optional JSON error response (requires
jsonfeature) - Custom Validator - Support for custom user validation logic
- Regex Paths - Regular expression path matching (requires
regexfeature) - Safety - Timing-safe password comparison (
timing-safe, enabled by default). Automatic password memory cleanup usingzeroizecrate (secure-memory, enabled by default)
Installation
Add the dependency in your Cargo.toml:
[]
= "0"
Enable optional features if needed:
[]
= { = "0", = ["bcrypt", "regex"] }
Quick Start
Basic Usage
use web;
use BasicAuthBuilder;
use HashMap;
async
async
async
Using the Builder Pattern
use ;
use HashMap;
let mut users = new;
users.insert;
let filter = new
.skip_prefix
.skip_exact
.skip_suffix;
let auth = new
.users
.realm
.path_filter
.log_failures
.max_header_size
.build
.unwrap;
Regex Path Filtering
Enable the regex feature in Cargo.toml:
[]
= { = "0", = ["regex"] }
use ;
let filter = new
.skip_regex.unwrap;
let auth = new
.user
.path_filter
.build
.unwrap;
BCrypt Password Support
Enable the bcrypt feature in Cargo.toml:
[]
= { = "0", = ["bcrypt"] }
use ;
use Arc;
let mut validator = new;
validator.add_user_with_password.unwrap;
let auth = new
.validator
.realm
.build
.unwrap;
Custom Validator
use ;
use Arc;
use Future;
use Pin;
;
let auth = new
.validator
.realm
.build
.unwrap;
Getting User Information
Get authenticated user information in the request handler:
use web;
use ;
async
PathFilter Builder Pattern
You can use the PathFilter builder for convenient filter creation:
use PathFilter;
let filter = new
.skip_exact
.skip_exact
.skip_prefix
.skip_suffix
.skip_suffix;
Common Skip Paths
Use built-in common skip paths for typical web applications (health checks, static assets, etc.):
use ;
// Create a filter with common web paths
let common_filter = new
.skip_exact
.skip_exact
.skip_exact
.skip_prefix
.skip_prefix
.skip_suffix
.skip_suffix
.skip_suffix
.skip_suffix
.skip_suffix;
let auth = new
.user
.path_filter
.build
.unwrap;
Error Handling
When authentication fails, the middleware returns HTTP 401 status code and corresponding error information:
Error types include:
MissingHeader- Missing Authorization headerInvalidFormat- Invalid Authorization header formatInvalidBase64- Invalid Base64 encodingInvalidCredentials- Invalid user credentialsValidationFailed- User validation failed
Configuration
Advanced Security Configuration
use ;
use Duration;
// Production-ready configuration with security hardening
let cache_config = new
.max_size
.ttl_minutes
.cleanup_interval_seconds;
// Common paths to skip authentication
let skip_paths = new
.skip_exact
.skip_exact
.skip_prefix
.skip_suffix
.skip_suffix;
let auth = new
.users_from_file // Load users from file
.realm
.with_cache
.max_concurrent_validations // Prevent resource exhaustion
.validation_timeout
.rate_limit_per_ip // 10 req/min per IP
.log_usernames_in_production // Security: no username logging
.path_filter // Skip health checks, assets
.build
.unwrap;
Security Best Practices
- Memory Security: The
secure-memoryfeature (enabled by default) automatically clears password data from memory after use - Cache Security: Cache keys are SHA256-hashed with application-specific salt to prevent rainbow table attacks
- Production Logging: Set
log_usernames_in_production(false)to prevent username leakage in production logs - DoS Protection: Configure rate limiting and concurrent validation limits to prevent resource exhaustion
Cache Configuration
Cache is enabled by default (unless disabled via builder/config):
use ;
// High-traffic configuration
let cache_config = new
.max_size // Large cache for busy servers
.ttl_minutes // Short TTL for security
.cleanup_interval_seconds // Frequent cleanup
.enable_stats; // Monitor cache performance
let auth = new
.user
.with_cache
.build
.unwrap;
License
Licensed under the MIT License. See LICENSE for details.