/
germanubis
/
jsonwebtoken
Обзор
Документация
Войти
/
germanubis
/
jsonwebtoken
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
examples/validation.rs
41 строка
1 KB
Vincent Prouillet
cargo fmt post edition bump
29 сен 2025, 22:37
29 сен 2025, 22:37
e72a3d4
Код
Авторство
О чём код?
use serde::{Deserialize, Serialize}; use jsonwebtoken::errors::ErrorKind; use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode}; #[derive(Debug, Serialize, Deserialize, Clone)] struct Claims { aud: String, sub: String, company: String, exp: u64, } fn main() { let key = b"secret"; let my_claims = Claims { aud: "me".to_owned(), sub: "b@b.com".to_owned(), company: "ACME".to_owned(), exp: 10000000000, }; let token = match encode(&Header::default(), &my_claims, &EncodingKey::from_secret(key)) { Ok(t) => t, Err(_) => panic!(), // in practice you would return the error }; let mut validation = Validation::new(Algorithm::HS256); validation.sub = Some("b@b.com".to_string()); validation.set_audience(&["me"]); validation.set_required_spec_claims(&["exp", "sub", "aud"]); let token_data = match decode::<Claims>(&token, &DecodingKey::from_secret(key), &validation) { Ok(c) => c, Err(err) => match *err.kind() { ErrorKind::InvalidToken => panic!("Token is invalid"), // Example on how to handle a specific error ErrorKind::InvalidIssuer => panic!("Issuer is invalid"), // Example on how to handle a specific error _ => panic!("Some other errors"), }, }; println!("{:?}", token_data.claims); println!("{:?}", token_data.header); }