Expand description
§r-token 🦀
A lightweight, zero-boilerplate authentication library for actix-web applications.
§Overview
r-token provides a minimalist approach to HTTP authentication in Rust web applications.
Inspired by Java’s Sa-Token, it leverages actix-web’s extractor
pattern to enable “parameter-as-authentication” - simply declare RUser in your handler
parameters, and authentication is handled automatically.
§Key Features
- Zero Boilerplate: No manual token validation or middleware setup required
- Type-Safe: Leverages Rust’s type system - if your handler receives
RUser, the user is authenticated - Non-Invasive: Uses actix-web’s
FromRequesttrait for seamless integration - Thread-Safe: Built on
Arc<Mutex<HashMap>>for safe concurrent access - Minimalist API: Only two core methods -
loginandlogout
§Quick Start
Add r-token to your Cargo.toml:
[dependencies]
r-token = "0.1"
actix-web = "4"Then create your authentication endpoints:
use actix_web::{get, post, web, HttpResponse, HttpServer, App};
use r_token::{RTokenManager, RUser, RTokenError};
#[post("/login")]
async fn login(
manager: web::Data<RTokenManager>
) -> Result<HttpResponse, RTokenError> {
let token = manager.login("user_10086")?;
Ok(HttpResponse::Ok().body(token))
}
#[get("/profile")]
async fn profile(user: RUser) -> impl actix_web::Responder {
// If we reach here, the user is guaranteed to be authenticated
format!("Welcome, user: {}", user.id)
}
#[post("/logout")]
async fn logout(
manager: web::Data<RTokenManager>,
user: RUser,
) -> Result<HttpResponse, RTokenError> {
manager.logout(&user.token)?;
Ok(HttpResponse::Ok().body("Logged out successfully"))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let manager = RTokenManager::new();
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(manager.clone()))
.service(login)
.service(profile)
.service(logout)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}§How It Works
- Login: Call
RTokenManager::login()with a user ID to generate a UUID token - Authenticate: Add
RUserto any handler that requires authentication - Automatic Validation: actix-web verifies the
Authorizationheader before calling your handler - Logout: Call
RTokenManager::logout()to invalidate a token
§Authorization Header Format
Clients should include the token in the Authorization header:
Authorization: <token>Or with the Bearer prefix:
Authorization: Bearer <token>§Error Handling
- 401 Unauthorized: Returned when token is missing or invalid
- 500 Internal Server Error: Returned when
RTokenManageris not registered inapp_data RTokenError::MutexPoisoned: Returned when the internal lock is poisoned (rare)
Structs§
- RToken
Manager - The core token management component.
- RUser
- Represents an authenticated user.
Enums§
- RToken
Error - Errors that can occur during token management operations.