移除无用代码
This commit is contained in:
parent
6f0c0e5f96
commit
16b0ef900d
@ -1,98 +0,0 @@
|
||||
// claims
|
||||
use chrono::{Duration, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Claims {
|
||||
sub: i32, // 用户ID
|
||||
exp: usize, // Access Token过期时间戳
|
||||
r_exp: usize, // Refresh Token过期时间戳
|
||||
}
|
||||
|
||||
// 登录API
|
||||
async fn login(username: String, password: String) -> Result<(String, String), (StatusCode, String)> {
|
||||
// 模拟数据库查询
|
||||
let user = get_user_from_database(&username, &password)?;
|
||||
// 如果用户存在且密码正确
|
||||
let access_token_expiration = Utc::now() + Duration::minutes(15);
|
||||
let refresh_token_expiration = Utc::now() + Duration::days(30);
|
||||
|
||||
let access_claims = Claims {
|
||||
sub: user.id,
|
||||
exp: access_token_expiration.timestamp() as usize,
|
||||
r_exp: refresh_token_expiration.timestamp() as usize,
|
||||
};
|
||||
let refresh_claims = Claims {
|
||||
sub: user.id,
|
||||
exp: refresh_token_expiration.timestamp() as usize,
|
||||
r_exp: refresh_token_expiration.timestamp() as usize,
|
||||
};
|
||||
|
||||
let access_token = jsonwebtoken::encode(&jsonwebtoken::Header::default(), &access_claims, JWT_SECRET)?;
|
||||
let refresh_token = jsonwebtoken::encode(&jsonwebtoken::Header::default(), &refresh_claims, JWT_SECRET)?;
|
||||
|
||||
Ok((access_token, refresh_token))
|
||||
}
|
||||
|
||||
//中间件实现Token校验
|
||||
async fn authenticate_access_token<B>(req: Request<B>, next: Next<B>) -> Result<Response, (StatusCode, String)> {
|
||||
let auth_header = req.headers().get(header::AUTHORIZATION);
|
||||
let token = match auth_header {
|
||||
Some(header_value) => {
|
||||
let parts: Vec<&str> = header_value.to_str().unwrap_or("").split_whitespace().collect();
|
||||
if parts.len() != 2 || parts[0] != "Bearer" {
|
||||
return Err((StatusCode::BAD_REQUEST, "Invalid authorization header format".to_string()));
|
||||
}
|
||||
parts[1]
|
||||
},
|
||||
None => return Err((StatusCode::UNAUTHORIZED, "Missing authorization header".to_string())),
|
||||
};
|
||||
|
||||
let validation = Validation::default();
|
||||
match decode::<Claims>(token, &DecodingKey::from_secret(JWT_SECRET), &validation) {
|
||||
Ok(decoded) => {
|
||||
// 将Claims附加到请求扩展中,以便后续处理使用
|
||||
req.extensions_mut().insert(decoded.claims);
|
||||
Ok(next.run(req).await)
|
||||
},
|
||||
Err(_) => Err((StatusCode::UNAUTHORIZED, "Invalid token".to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
//刷新Token的API
|
||||
async fn refresh_token_handler(Json(payload): Json<Claims>) -> Result<String, (StatusCode, String)> {
|
||||
let user_id = payload.sub;
|
||||
// 在数据库中验证Refresh Token,确保它没有被使用过
|
||||
// 这里简化为仅检查用户ID
|
||||
if let Some(refresh_claims) = get_refresh_claims_from_database(user_id) {
|
||||
// 生成新的Access Token
|
||||
let access_token_expiration = Utc::now() + Duration::minutes(15);
|
||||
let access_claims = Claims {
|
||||
sub: user_id,
|
||||
exp: access_token_expiration.timestamp() as usize,
|
||||
r_exp: refresh_claims.r_exp,
|
||||
};
|
||||
let new_access_token = jsonwebtoken::encode(&jsonwebtoken::Header::default(), &access_claims, JWT_SECRET)?;
|
||||
Ok(new_access_token)
|
||||
} else {
|
||||
Err((StatusCode::UNAUTHORIZED, "Invalid or expired refresh token".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 组合路由和中间件
|
||||
use axum::{routing::post, Router};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let app = Router::new()
|
||||
.route("/login", post(login))
|
||||
.route("/refresh-token", post(refresh_token_handler))
|
||||
// 示例路由,假设所有路由都需要认证,除了登录和刷新Token
|
||||
.route("/protected-resource", post(|_| async { /* 处理逻辑 */ }))
|
||||
.layer(tower::ServiceBuilder::new().layer_fn(authenticate_access_token));
|
||||
|
||||
println!("Server running on http://localhost:3000");
|
||||
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user