Expand description
§r-token 🦀
r-token is a lightweight, non-invasive authentication library designed for Rust (actix-web).
r-token 是一个专为 Rust (actix-web) 设计的轻量级、无侵入式鉴权库。
§Design Philosophy | 设计理念
Inspired by Java’s Sa-Token, r-token provides an “out-of-the-box”, “parameter-as-authentication” minimalist experience.
设计灵感来源于 Java 的 Sa-Token,旨在提供一种“开箱即用“、“参数即鉴权“的极简体验。
§Features | 特性
- Minimal Integration | 极简集成: Initialize with just a few lines of code | 只需几行代码即可初始化
- Idiomatic Rust | Rust 风格: Leverages Actix’s
Extractormechanism, eliminating cumbersomeif/elsechecks | 利用 Actix 的Extractor机制,摆脱繁琐的if/else检查 - Non-invasive | 零侵入: Automatic authentication by declaring
RUserin handler parameters | 在 Handler 参数中声明RUser即可自动完成鉴权 - State Sharing | 状态共享: Thread-safe token management with
ArcandMutex| 基于Arc和Mutex实现线程安全的 Token 管理
§Quick Start | 快速开始
use actix_web::{get, post, web, HttpResponse, HttpServer, App};
use r_token::{RTokenManager, RUser};
// Login endpoint | 登录接口
#[post("/login")]
async fn login(manager: web::Data<RTokenManager>) -> impl actix_web::Responder {
let user_id = "10086";
let token = manager.login(user_id);
HttpResponse::Ok().body(format!("Login Success, Token: {}", token))
}
// Protected endpoint - Users without valid tokens can't access! | 受保护接口 - 没有有效 Token 的用户无法访问!
#[get("/info")]
async fn user_info(user: RUser) -> impl actix_web::Responder {
format!("Hello, User ID: {}", user.id)
}
// Logout endpoint | 注销接口
#[post("/logout")]
async fn logout(manager: web::Data<RTokenManager>, user: RUser) -> impl actix_web::Responder {
manager.logout(&user.token);
HttpResponse::Ok().body("Logout Success")
}
#[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(user_info)
.service(logout)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}Structs§
- RToken
Manager - Token Manager | Token 管理器
- RUser
- Authenticated User Information | 已认证用户信息