Created
June 5, 2024 14:43
-
-
Save DefectingCat/7aa59d2a96eb2d85a340ff14c8dc4d33 to your computer and use it in GitHub Desktop.
rust jsonwebtoken
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::OnceLock; | |
use jsonwebtoken::{DecodingKey, EncodingKey, Header}; | |
use serde::{Deserialize, Serialize}; | |
pub struct Keys { | |
pub encoding: EncodingKey, | |
pub decoding: DecodingKey, | |
} | |
impl Keys { | |
fn new(secret: &[u8]) -> Self { | |
Self { | |
encoding: EncodingKey::from_secret(secret), | |
decoding: DecodingKey::from_secret(secret), | |
} | |
} | |
} | |
static KEYS: OnceLock<Keys> = OnceLock::new(); | |
pub fn get_jwt_keys() -> &'static Keys { | |
let secret = std::env::var("LIMOS_SECRET").expect("LIMOS_SECRET must be set"); | |
KEYS.get_or_init(|| Keys::new(secret.as_bytes())) | |
} | |
#[derive(Debug, Serialize, Deserialize)] | |
#[serde(rename_all = "camelCase")] | |
pub struct Claims { | |
/// 当前用户 uuid | |
pub uuid: String, | |
/// token 发放时间 | |
pub iss: i64, | |
/// token 过期时间 | |
pub exp: u128, | |
} | |
pub fn encode(claims: &Claims) -> anyhow::Result<String> { | |
let key = get_jwt_keys(); | |
let token = jsonwebtoken::encode(&Header::default(), claims, &key.encoding)?; | |
Ok(token) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment