From 40f8cd770de00fe9e13624b4b4d0b349ea4e3151 Mon Sep 17 00:00:00 2001 From: phoenix Date: Sun, 6 Apr 2025 20:25:02 -0400 Subject: [PATCH] Added expiration claim to token --- src/token_stuff/mod.rs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/token_stuff/mod.rs b/src/token_stuff/mod.rs index 996ade9..66b4045 100644 --- a/src/token_stuff/mod.rs +++ b/src/token_stuff/mod.rs @@ -4,6 +4,8 @@ use josekit::{ jwt::{self, JwtPayload}, }; +use time; + pub const TOKENTYPE: &str = "JWT"; pub const KEY_ENV: &str = "SECRET_KEY"; pub const MESSAGE: &str = "Something random"; @@ -16,6 +18,13 @@ pub fn get_key() -> Result { Ok(key) } +pub fn get_expiration() -> time::Result { + let now = time::OffsetDateTime::now_utc(); + let epoch = time::OffsetDateTime::UNIX_EPOCH; + let since_the_epoch = now - epoch; + Ok(since_the_epoch) +} + pub fn create_token(provided_key: &String) -> Result { let mut header = JwsHeader::new(); header.set_token_type(TOKENTYPE); @@ -24,6 +33,16 @@ pub fn create_token(provided_key: &String) -> Result payload.set_subject(MESSAGE); payload.set_issuer(ISSUER); payload.set_audience(vec![AUDIENCE]); + match get_expiration() { + Ok(duration) => { + let expire = duration.whole_seconds(); + let _ = payload.set_claim( + "expiration", + Some(serde_json::to_value(expire.to_string()).unwrap()), + ); + } + Err(_) => {} + }; let key: String = if provided_key.is_empty() { get_key().unwrap() @@ -32,9 +51,7 @@ pub fn create_token(provided_key: &String) -> Result }; let signer = Hs256.signer_from_bytes(key.as_bytes()).unwrap(); - let jwt = josekit::jwt::encode_with_signer(&payload, &header, &signer).unwrap(); - - Ok(jwt) + Ok(josekit::jwt::encode_with_signer(&payload, &header, &signer).unwrap()) } pub fn verify_token(key: &String, token: &String) -> bool {