Crate r_token

Crate r_token 

Source
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 FromRequest trait for seamless integration
  • Thread-Safe: Built on Arc<Mutex<HashMap>> for safe concurrent access
  • Minimalist API: Only two core methods - login and logout

§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

  1. Login: Call RTokenManager::login() with a user ID to generate a UUID token
  2. Authenticate: Add RUser to any handler that requires authentication
  3. Automatic Validation: actix-web verifies the Authorization header before calling your handler
  4. 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 RTokenManager is not registered in app_data
  • RTokenError::MutexPoisoned: Returned when the internal lock is poisoned (rare)

Structs§

RTokenManager
The core token management component.
RUser
Represents an authenticated user.

Enums§

RTokenError
Errors that can occur during token management operations.