Last active: 7 months ago
rust jsonwebtoken
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)
}