jsonwebtoken/examples/validation.rs

43 lines
1.2 KiB
Rust
Raw Normal View History

2015-11-02 18:27:28 -05:00
extern crate jsonwebtoken as jwt;
2017-04-12 21:29:30 -04:00
#[macro_use]
extern crate serde_derive;
2015-11-02 15:34:11 -05:00
2017-04-22 02:21:16 -04:00
use jwt::{encode, decode, Header, Validation};
use jwt::errors::{ErrorKind};
2015-11-02 15:34:11 -05:00
#[derive(Debug, Serialize, Deserialize)]
2015-11-02 15:34:11 -05:00
struct Claims {
sub: String,
2018-10-28 14:54:35 -04:00
company: String,
exp: usize,
2015-11-02 15:34:11 -05:00
}
fn main() {
let my_claims = Claims {
sub: "b@b.com".to_owned(),
2018-10-28 14:54:35 -04:00
company: "ACME".to_owned(),
exp: 10000000000,
2015-11-02 15:34:11 -05:00
};
2015-11-02 16:04:58 -05:00
let key = "secret";
2017-04-10 23:54:32 -04:00
let token = match encode(&Header::default(), &my_claims, key.as_ref()) {
2015-11-03 11:00:52 -05:00
Ok(t) => t,
Err(_) => panic!() // in practice you would return the error
};
2017-10-22 07:20:01 -04:00
let validation = Validation {
sub: Some("b@b.com".to_string()),
..Validation::default()
};
2017-04-22 02:21:16 -04:00
let token_data = match decode::<Claims>(&token, key.as_ref(), &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
_ => 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
}