pub struct RUser {
pub id: String,
pub token: String,
}Expand description
Authenticated User Information | 已认证用户信息
RUser is the core concept of r-token. It implements actix-web’s FromRequest trait,
enabling “parameter-as-authentication” by using it directly as a handler parameter.
RUser 是 r-token 最核心的概念,它实现了 actix-web 的 FromRequest trait,
可以作为 Handler 的参数直接使用,实现“参数即鉴权“的效果。
§How It Works | 工作原理
When you declare RUser as a handler parameter, actix-web automatically:
当你在 Handler 参数中声明 RUser 时,actix-web 会自动:
- Extracts the Token from the
Authorizationheader | 从请求的Authorizationheader 中提取 Token - Validates the Token through
RTokenManager| 通过RTokenManager验证 Token 的有效性 - If valid, creates an
RUserinstance and passes it to your handler | 如果验证通过,创建RUser实例并传递给你的 Handler - If invalid, returns 401 Unauthorized without calling the handler | 如果验证失败,直接返回 401 Unauthorized,Handler 不会被调用
§Zero-Intrusion Design | 零侵入式设计
You don’t need any if/else checks in your business code to verify if a user is logged in.
If a parameter has RUser, the user is guaranteed to be authenticated!
你不需要在业务代码中写任何 if/else 来检查用户是否登录,
只要参数里有 RUser,就保证用户一定是已登录的!
§Example | 示例
use actix_web::{get, HttpResponse};
use r_token::RUser;
#[get("/protected")]
async fn protected_route(user: RUser) -> impl actix_web::Responder {
// If we get here, user is guaranteed to be valid! | 能进到这里,user 一定是合法的!
HttpResponse::Ok().body(format!("Welcome, user {}", user.id))
}Fields§
§id: StringUser ID | 用户 ID
Corresponds to the user identifier passed during login | 对应登录时传入的用户标识符
token: StringUser’s Token | 用户的 Token
The Token string extracted from the Authorization header | 从 Authorization header 中提取的 Token 字符串
Trait Implementations§
Source§impl FromRequest for RUser
FromRequest Trait Implementation | FromRequest trait 实现
impl FromRequest for RUser
FromRequest Trait Implementation | FromRequest trait 实现
This is the key to r-token’s “parameter-as-authentication” feature.
这是 r-token 实现“参数即鉴权“的关键。
§Execution Flow | 执行流程
When actix-web receives a request and finds a handler needs an RUser parameter,
it automatically executes this logic:
当 actix-web 收到请求并发现 Handler 需要 RUser 参数时,会自动执行这里的逻辑:
- Get Token Manager | 获取 Token 管理器: Extract
RTokenManagerfromapp_data| 从app_data中提取RTokenManager - Extract Token | 提取 Token: Get Token from
Authorizationheader (supportsBearerprefix) | 从Authorizationheader 中获取 Token(支持Bearer前缀) - Validate Token | 验证 Token: Check if Token exists in manager’s storage | 检查 Token 是否存在于管理器的存储中
- Return Result | 返回结果:
- Success → Create
RUserinstance, handler executes normally | 成功 → 创建RUser实例,Handler 正常执行 - Failure → Return 401 Unauthorized, handler is not called | 失败 → 返回 401 Unauthorized,Handler 不会被调用
- Success → Create
§Error Handling | 错误处理
500 Internal Server Error: Token manager not injected intoapp_data| Token 管理器未注入到app_data401 Unauthorized: Token missing or invalid | Token 缺失或无效