UserInfo Extractor
10/30/24About 1 min
UserInfo Extractor
UserInfo is the core tool for handling user identity verification in our application. It's not just a simple data structure but a powerful Axum Extractor.
Its main goal is: to completely strip the complex logic of authentication from business handlers, making our code cleaner, safer, and easier to maintain.
Core Concept
If you request UserInfo in your function signature, you can be 100% sure that the user is a legitimate, authenticated user when your function executes. No manual checks needed.
Struct Definition
use serde::{Serialize, Deserialize};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UserInfo {
pub username: String,
pub uid: i64, // User ID
pub did: i64, // Device ID
pub rid: i64, // Role ID
pub token_id: i64, // Current Token's unique ID
}Trait Derivation Explanation
Debug: Allows printingUserInfoinstances with{:?}for debugging.Clone: Allows creating a full copy ofUserInfo.Default: Allows creating a default, emptyUserInfoinstance.Serialize,Deserialize: Provided byserdefor JSON serialization/deserialization.
Usage
Using UserInfo in an Axum Handler is simple: just add it as a function parameter.
✅ Recommended
use crate::extractors::UserInfo;
pub async fn get_profile(user_info: UserInfo) -> Response {
// user_info.uid, user_info.username are guaranteed to be valid
ApiResponse::ok(user_info)
}❌ Not Recommended (Manual extraction)
pub async fn get_profile(
State(state): State<AppState>,
headers: HeaderMap,
) -> Response {
let token = match headers.get("Authorization") {
Some(val) => val.to_str().unwrap_or(""),
None => return ApiResponse::unauthorized("Missing Authorization header"),
};
// ...manual token parsing and validation...
// Error-prone and verbose
}The advantage of the UserInfo extractor is clear.
Core Advantages
- Clean Code: Frees handlers from tedious authentication logic.
- Separation of Concerns: Authentication logic is encapsulated in the extractor; business logic is in the handler.
- Secure by Default: Eliminates the risk of forgetting authentication checks in handlers.
- Easy to Maintain: Future auth changes only need modification in one place.
- Type-Safe: You get a complete, strongly-typed
UserInfostruct.
How It Works
UserInfo implements Axum's FromRequestParts Trait. When Axum prepares to call your handler:
- It sees the
UserInfoparameter and calls its extraction logic - The logic automatically parses
Authorization: Bearer <token>from request headers - If token is missing or malformed, returns
401 Unauthorized - If token exists, validates it and retrieves user info
- If token is invalid/expired, returns
401 Unauthorized - Only after all validation succeeds does it construct a
UserInfoinstance and inject it into your handler