A production-ready, secure REST API built with Rust, featuring JWT authentication, password hashing with Argon2, and CORS support.
THIS SOFTWARE IS PROVIDED "AS IS" FOR EDUCATIONAL AND DEMONSTRATION PURPOSES ONLY.
This project is a reference implementation and should not be used directly in production without:
- Proper security auditing
- Thorough testing in your specific environment
- Additional security hardening based on your requirements
- Regular security updates and maintenance
The author assumes no liability for any damages, security breaches, or data loss that may occur from using this software. Use at your own risk.
- JWT Authentication: Stateless authentication using JSON Web Tokens
- Argon2 Password Hashing: Industry-standard password hashing algorithm
- Rate Limiting: In-memory IP-based rate limiting on authentication endpoints
- CORS Configuration: Cross-Origin Resource Sharing protection
- Secure Headers: HTTP security headers implementation
- Token Expiration: Automatic token expiration (24 hours)
- Environment Variables: Sensitive configuration via environment variables
- Persistent Storage: Redb embedded database for user data
- actix-web: High-performance async web framework
- tokio: Async runtime
- jsonwebtoken: JWT implementation
- argon2: Password hashing
- serde: Serialization/deserialization
- chrono: Date and time handling
- dotenvy: Environment variable management
- redb: High-performance embedded database
- governor: Rate limiting
secure-rust-api/
βββ src/
β βββ handlers/ # Request handlers
β β βββ auth.rs # Authentication endpoints
β β βββ api.rs # API endpoints
β βββ middleware/ # Custom middleware
β β βββ auth.rs # JWT authentication middleware
β βββ models/ # Data models
β β βββ user.rs # User and Claims models
β βββ utils/ # Utility functions
β β βββ auth.rs # Auth utilities (hashing, JWT)
β βββ main.rs # Application entry point
βββ Cargo.toml # Dependencies
βββ .env.example # Environment variables template
βββ README.md # This file
- Rust 1.70+ (install from rustup.rs)
- Cargo (comes with Rust)
-
Clone the repository:
git clone https://github.com/quintbotha/secure-rust-api.git cd secure-rust-api -
Create environment file:
cp .env.example .env
-
Edit
.envand set a strong JWT secret:JWT_SECRET=your-very-strong-random-secret-key-here
-
Build the project:
cargo build --release
-
Run the server:
cargo run
The server will start on http://127.0.0.1:8080
GET /api/healthResponse:
{
"status": "healthy",
"timestamp": "2024-01-01T12:00:00Z"
}POST /api/auth/register
Content-Type: application/json
{
"username": "john_doe",
"email": "john@example.com",
"password": "securepassword123"
}Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"username": "john_doe",
"email": "john@example.com"
}
}POST /api/auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "password123"
}Response: Same as register
These endpoints require a valid JWT token in the Authorization header.
GET /api/secure/data
Authorization: Bearer <your-jwt-token>Response:
{
"message": "This is protected data",
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"data": ["Sensitive item 1", "Sensitive item 2", "Sensitive item 3"]
}GET /api/secure/profile
Authorization: Bearer <your-jwt-token>Response:
{
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"email": "john@example.com",
"exp": 1704117600
}PATCH /api/secure/profile
Authorization: Bearer <your-jwt-token>
Content-Type: application/json
{
"username": "new_username",
"email": "newemail@example.com"
}Response:
{
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"username": "new_username",
"email": "newemail@example.com",
"updated_at": "2024-01-01T12:00:00Z"
}POST /api/secure/change-password
Authorization: Bearer <your-jwt-token>
Content-Type: application/json
{
"old_password": "currentpassword123",
"new_password": "newpassword456"
}Response:
{
"message": "Password changed successfully",
"changed_at": "2024-01-01T12:00:00Z"
}DELETE /api/secure/account
Authorization: Bearer <your-jwt-token>Response:
{
"message": "Account deleted successfully",
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"deleted_at": "2024-01-01T12:00:00Z"
}curl -X POST http://localhost:8080/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"email": "test@example.com",
"password": "securepass123"
}'curl -X POST http://localhost:8080/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "password123"
}'# Replace <TOKEN> with the JWT from login/register
curl -X GET http://localhost:8080/api/secure/data \
-H "Authorization: Bearer <TOKEN>"curl -X PATCH http://localhost:8080/api/secure/profile \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"username": "newusername",
"email": "newemail@example.com"
}'curl -X POST http://localhost:8080/api/secure/change-password \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"old_password": "oldpassword123",
"new_password": "newpassword456"
}'curl -X DELETE http://localhost:8080/api/secure/account \
-H "Authorization: Bearer <TOKEN>"Edit .env to customize:
# Server Configuration
HOST=127.0.0.1 # Bind address
PORT=8080 # Port number
# JWT Configuration
JWT_SECRET=your-secret-key # Change this!
# Logging
RUST_LOG=info # Log level (debug, info, warn, error)- Change the JWT Secret: Always use a strong, random secret in production
- Use HTTPS: Deploy behind a reverse proxy with TLS/SSL
- Rate Limiting: Implement rate limiting for authentication endpoints
- Database: Connect to a real database instead of in-memory storage
- Input Validation: Add comprehensive input validation
- Error Handling: Avoid exposing sensitive information in error messages
- Token Refresh: Implement refresh tokens for long-lived sessions
- Password Requirements: Enforce strong password policies
cargo runRUST_LOG=debug cargo runcargo fmtcargo clippycargo test# Build and start with Docker Compose
docker-compose up -d
# View logs
docker-compose logs -f api
# Stop services
docker-compose downSee DOCKER.md for complete Docker deployment guide.
- π Distroless base image (minimal attack surface)
- π€ Non-root user (UID 65532)
- π¦ Multi-stage build (~50MB final image)
- π Health checks
- πΎ Persistent volumes
-
Build optimized release binary:
cargo build --release
-
Binary location:
./target/release/secure-rust-api -
Set environment variables securely (never commit
.env) -
Use a process manager (systemd, PM2, etc.)
-
Deploy behind a reverse proxy (nginx, Caddy)
See DOCKER.md for:
- Reverse proxy setup
- Resource limits
- Security hardening
- Backup/restore procedures
This project is licensed under the MIT License - see the LICENSE file for details.
Key Points:
- β Free to use, modify, and distribute
- β Commercial use allowed
- β No warranty provided
- β Author not liable for damages
Contributions welcome! Please feel free to submit a Pull Request.
By contributing, you agree that your contributions will be licensed under the MIT License.