46 lines
1.3 KiB
Rust
46 lines
1.3 KiB
Rust
use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
struct Claims {
|
|
sub: String,
|
|
tenant_id: String,
|
|
exp: usize,
|
|
iat: usize,
|
|
iss: String,
|
|
}
|
|
|
|
fn main() {
|
|
let issuer = std::env::var("JWT_ISSUER").unwrap_or_else(|_| "iam-service".to_string());
|
|
let kid = std::env::var("JWT_KEY_ID").unwrap_or_else(|_| "default".to_string());
|
|
let private_pem = std::env::var("JWT_PRIVATE_KEY_PEM").expect("JWT_PRIVATE_KEY_PEM is required");
|
|
let tenant_id = std::env::var("TENANT_ID").unwrap_or_else(|_| Uuid::new_v4().to_string());
|
|
let user_id = std::env::var("USER_ID").unwrap_or_else(|_| Uuid::new_v4().to_string());
|
|
|
|
let now = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.unwrap()
|
|
.as_secs() as usize;
|
|
|
|
let claims = Claims {
|
|
sub: user_id,
|
|
tenant_id,
|
|
exp: now + 15 * 60,
|
|
iat: now,
|
|
iss: issuer.clone(),
|
|
};
|
|
|
|
let mut header = Header::new(Algorithm::RS256);
|
|
header.kid = Some(kid);
|
|
let token = encode(
|
|
&header,
|
|
&claims,
|
|
&EncodingKey::from_rsa_pem(private_pem.as_bytes()).expect("invalid private key pem"),
|
|
)
|
|
.expect("failed to sign token");
|
|
|
|
println!("{}", token);
|
|
}
|