feat: add redis

This commit is contained in:
2025-08-29 21:42:29 +08:00
parent af68d94efa
commit dc60a0a4bd
10 changed files with 875 additions and 52 deletions

View File

@ -2,7 +2,7 @@ use axum::{http::HeaderMap, http::header::AUTHORIZATION};
use chrono::{Utc, Duration as ChronoDuration};
use jsonwebtoken::{EncodingKey, DecodingKey, Header, Validation};
use serde::{Serialize, Deserialize};
use crate::error::AppError;
use crate::{error::AppError, redis::TokenRedis};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Claims {
@ -37,6 +37,21 @@ impl<S> axum::extract::FromRequestParts<S> for AuthUser where S: Send + Sync + '
let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
let claims = decode_token(token, &secret)?;
if claims.typ != "access" { return Err(AppError::Unauthorized); }
// 验证token是否在Redis中存在可选添加环境变量控制是否启用Redis验证
let redis_validation_enabled = std::env::var("REDIS_TOKEN_VALIDATION")
.unwrap_or_else(|_| "true".to_string())
.parse::<bool>()
.unwrap_or(true);
if redis_validation_enabled {
let is_valid = TokenRedis::validate_access_token(token, claims.uid).await
.unwrap_or(false);
if !is_valid {
return Err(AppError::Unauthorized);
}
}
Ok(AuthUser { uid: claims.uid, username: claims.sub })
}
}