jsonwebtoken/examples/validation.rs

40 lines
1.3 KiB
Rust
Raw Normal View History

2019-11-03 10:46:08 -05:00
use jsonwebtoken::errors::ErrorKind;
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
2019-11-03 10:46:08 -05:00
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
2015-11-02 15:34:11 -05:00
struct Claims {
aud: String,
2015-11-02 15:34:11 -05:00
sub: String,
2018-10-28 14:54:35 -04:00
company: String,
exp: usize,
2015-11-02 15:34:11 -05:00
}
fn main() {
2019-12-29 12:42:35 -05:00
let key = b"secret";
let my_claims = Claims {
aud: "me".to_owned(),
sub: "b@b.com".to_owned(),
company: "ACME".to_owned(),
exp: 10000000000,
};
2019-12-29 12:42:35 -05:00
let token = match encode(&Header::default(), &my_claims, &EncodingKey::from_secret(key)) {
2015-11-03 11:00:52 -05:00
Ok(t) => t,
2018-10-28 14:58:35 -04:00
Err(_) => panic!(), // in practice you would return the error
2015-11-03 11:00:52 -05:00
};
let mut validation = Validation::new(Algorithm::HS256);
validation.sub = Some("b@b.com".to_string());
validation.set_audience(&["me"]);
2019-12-29 15:50:06 -05:00
let token_data = match decode::<Claims>(&token, &DecodingKey::from_secret(key), &validation) {
2015-11-03 11:00:52 -05:00
Ok(c) => c,
Err(err) => match *err.kind() {
2018-10-28 14:54:35 -04:00
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
2018-10-28 14:58:35 -04:00
_ => panic!("Some other errors"),
},
2015-11-03 11:00:52 -05:00
};
println!("{:?}", token_data.claims);
println!("{:?}", token_data.header);
2015-11-02 15:34:11 -05:00
}