From 8f315ac1acb3d159e3d8bb5d20c7fad425655145 Mon Sep 17 00:00:00 2001 From: hys Date: Wed, 11 Dec 2024 21:06:22 +0800 Subject: [PATCH] fix: change jwt claims exp/iat to timestamp --- auth/src/lib.rs | 4 ++-- server/src/infra/auth_service.rs | 11 +++++++---- server/src/main.rs | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/auth/src/lib.rs b/auth/src/lib.rs index c6bb82e0..97c5a594 100644 --- a/auth/src/lib.rs +++ b/auth/src/lib.rs @@ -226,8 +226,8 @@ pub mod types { #[derive(Clone, Serialize, Deserialize)] pub struct JWTClaims { - pub exp: DateTime, - pub iat: DateTime, + pub exp: i64, + pub iat: i64, pub user: String, pub groups: HashSet, } diff --git a/server/src/infra/auth_service.rs b/server/src/infra/auth_service.rs index 390b167d..54694b21 100644 --- a/server/src/infra/auth_service.rs +++ b/server/src/infra/auth_service.rs @@ -54,16 +54,17 @@ async fn create_jwt( user: &UserId, groups: HashSet, ) -> SignedToken { + let exp_utc = Utc::now() + chrono::Duration::days(1); let claims = JWTClaims { - exp: Utc::now() + chrono::Duration::days(1), - iat: Utc::now(), + exp: exp_utc.timestamp(), + iat: Utc::now().timestamp(), user: user.to_string(), groups: groups .into_iter() .map(|g| g.display_name.into_string()) .collect(), }; - let expiry = claims.exp.naive_utc(); + let expiry = exp_utc.naive_utc(); let header = jwt::Header { algorithm: jwt::AlgorithmType::Hs512, ..Default::default() @@ -685,7 +686,9 @@ pub(crate) fn check_if_token_is_valid( ) -> Result { let token: Token<_> = VerifyWithKey::verify_with_key(token_str, &state.jwt_key) .map_err(|_| ErrorUnauthorized("Invalid JWT"))?; - if token.claims().exp.lt(&Utc::now()) { + let naive_datetime:NaiveDateTime = NaiveDateTime::from_timestamp_opt(token.claims().exp,0).unwrap(); + let exp_utc = DateTime::::from_utc(naive_datetime,Utc); + if exp_utc.lt(&Utc::now()) { return Err(ErrorUnauthorized("Expired JWT")); } if token.header().algorithm != jwt::AlgorithmType::Hs512 { diff --git a/server/src/main.rs b/server/src/main.rs index b6ab115d..a0692706 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -26,7 +26,7 @@ use crate::{ use actix::Actor; use actix_server::ServerBuilder; use anyhow::{anyhow, bail, Context, Result}; -use futures_util::TryFutureExt; +//use futures_util::TryFutureExt; use sea_orm::{Database, DatabaseConnection}; //use secstr::{SecUtf8}; use tracing::*;