Ruts: Rust Tower Session for HTTP Applications
Ruts is a robust, flexible session management library for Rust web applications. It provides a seamless way to handle cookie sessions in tower-based web frameworks, with a focus on security, performance, and ease of use.
Features
- 🚀 High-performance session management
- 🔒 Secure by default with configurable options
- 🔄 Built-in Redis session store support
- 🛠 Flexible API supporting custom session stores
- ⚡ Optimized for tower-based frameworks like axum
- 🍪 Comprehensive cookie management
Installation
Add the following to your Cargo.toml:
[]
= "0.5.4"
Quick Start
Here's a basic example using ruts with axum:
use ;
use ;
use RedisStore;
use Client;
use Arc;
use ClientLike;
use CookieManagerLayer;
async
async
Session Management
Basic Operations
// Get session data
let value: ValueType = session.get.await?;
// Insert new data
session.insert.await?;
// Prepare a new session ID for the next insert
let new_id = session.prepare_regenerate;
session.insert.await?;
// Update existing data
session.update.await?;
// Prepare a new session ID for the next update
let new_id = session.prepare_regenerate;
session.update.await?;
// Remove data
session.remove.await?;
// Delete entire session
session.delete.await?;
// Regenerate session ID (for security)
session.regenerate.await?;
// Update session expiry
session.expire
// Get session ID
session.id
Redis Store (Default session store)
A Redis-backed session store implementation.
Requirements
- Redis 7.4 or later (required for field-level expiration using HEXPIRE)
- For Redis < 7.4, field-level expiration will not be available
use RedisStore;
let store = new;
Cookie Configuration
let cookie_options = build
.name
.http_only
.same_site
.secure
.max_age // 2 hours
.path
.domain; // Optional
Important Notes
Middleware Ordering
When using cookie-based sessions, the SessionLayer must be applied before the CookieManagerLayer:
app.layer // First: Session layer
.layer; // Then: Cookie layer on top
Security Best Practices
- Enable HTTPS in production (set
secure: truein cookie options) - Use appropriate
SameSitecookie settings - Add session expiration
- Regularly regenerate session IDs
- Set proper cookie attributes (
http_only: true)
Error Handling
The library provides a comprehensive error type for handling various session-related errors:
match session..await
Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
License
This project is licensed under the MIT License - see the LICENSE file for details.