Ruts: Rust Tower Session for HTTP Applications
Installation
Add the following to your Cargo.toml:
[]
= "0.5.9"
Quick Start
Here's a basic example 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;
Serialization
Ruts supports two serialization backends for session data storage:
bincode (default) - Fast binary serialization
messagepack - Cross-language compatible serialization
To use MessagePack instead of the default bincode, add this to your Cargo.toml:
[]
= { = "0.5.9", = false, = ["axum", "redis-store", "messagepack"] }
Cookie Configuration
let cookie_options = build
.name
.http_only
.same_site
.secure
.max_age // 2 hours
.path
.domain;
Important Notes
Middleware Ordering
The SessionLayer must be applied before the CookieManagerLayer:
app.layer // First: SessionLayer
.layer; // Then CookieManagerLayer
Security Best Practices
- Enable HTTPS in production (set
secure: truein cookie options) - Use appropriate
SameSitecookie settings - Add session expiration
- Regularly regenerate session IDs
- Enable HTTP Only mode in production (set
http_only: true)
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.