2019-11-03 10:46:08 -05:00
|
|
|
use serde::{Deserialize, Serialize};
|
2015-12-19 20:16:52 -05:00
|
|
|
|
2019-11-03 10:46:08 -05:00
|
|
|
use jsonwebtoken::errors::ErrorKind;
|
2019-12-29 15:50:06 -05:00
|
|
|
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
|
2015-12-19 20:16:52 -05:00
|
|
|
|
2017-01-09 00:50:51 -05:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
2015-12-19 20:16:52 -05:00
|
|
|
struct Claims {
|
|
|
|
sub: String,
|
2018-10-28 14:54:35 -04:00
|
|
|
company: String,
|
|
|
|
exp: usize,
|
2015-12-19 20:16:52 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2018-10-28 14:58:35 -04:00
|
|
|
let my_claims =
|
|
|
|
Claims { sub: "b@b.com".to_owned(), company: "ACME".to_owned(), exp: 10000000000 };
|
2019-05-15 10:20:09 -04:00
|
|
|
let key = b"secret";
|
2015-12-19 20:16:52 -05:00
|
|
|
|
2021-02-20 04:00:51 -05:00
|
|
|
let header =
|
|
|
|
Header { kid: Some("signing_key".to_owned()), alg: Algorithm::HS512, ..Default::default() };
|
2015-12-19 20:16:52 -05:00
|
|
|
|
2019-12-29 12:42:35 -05:00
|
|
|
let token = match encode(&header, &my_claims, &EncodingKey::from_secret(key)) {
|
2015-12-19 20:16:52 -05:00
|
|
|
Ok(t) => t,
|
2018-10-28 14:58:35 -04:00
|
|
|
Err(_) => panic!(), // in practice you would return the error
|
2015-12-19 20:16:52 -05:00
|
|
|
};
|
2017-04-13 03:36:32 -04:00
|
|
|
println!("{:?}", token);
|
2015-12-19 20:16:52 -05:00
|
|
|
|
2019-12-29 15:50:06 -05:00
|
|
|
let token_data = match decode::<Claims>(
|
|
|
|
&token,
|
|
|
|
&DecodingKey::from_secret(key),
|
|
|
|
&Validation::new(Algorithm::HS512),
|
|
|
|
) {
|
2019-11-06 17:32:13 -05:00
|
|
|
Ok(c) => c,
|
|
|
|
Err(err) => match *err.kind() {
|
|
|
|
ErrorKind::InvalidToken => panic!(), // Example on how to handle a specific error
|
|
|
|
_ => panic!(),
|
|
|
|
},
|
|
|
|
};
|
2015-12-19 20:16:52 -05:00
|
|
|
println!("{:?}", token_data.claims);
|
|
|
|
println!("{:?}", token_data.header);
|
|
|
|
}
|