2019-01-31 23:11:20 -05:00
|
|
|
extern crate jsonwebtoken;
|
|
|
|
#[macro_use]
|
|
|
|
extern crate serde_derive;
|
|
|
|
extern crate chrono;
|
|
|
|
|
|
|
|
use chrono::Utc;
|
2019-06-16 12:00:00 -04:00
|
|
|
use jsonwebtoken::{decode, encode, sign, verify, Algorithm, Header, Key, Validation};
|
2019-01-31 23:11:20 -05:00
|
|
|
|
|
|
|
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
|
2019-07-06 14:36:32 -04:00
|
|
|
pub struct Claims {
|
2019-01-31 23:11:20 -05:00
|
|
|
sub: String,
|
|
|
|
company: String,
|
|
|
|
exp: i64,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn round_trip_sign_verification() {
|
|
|
|
let privkey = include_bytes!("private_ecdsa_key.pk8");
|
2019-06-16 11:51:43 -04:00
|
|
|
let encrypted = sign("hello world", Key::Pkcs8(&privkey[..]), Algorithm::ES256).unwrap();
|
2019-01-31 23:11:20 -05:00
|
|
|
let pubkey = include_bytes!("public_ecdsa_key.pk8");
|
2019-06-16 11:51:43 -04:00
|
|
|
let is_valid = verify(&encrypted, "hello world", Key::Pkcs8(pubkey), Algorithm::ES256).unwrap();
|
2019-01-31 23:11:20 -05:00
|
|
|
assert!(is_valid);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn round_trip_claim() {
|
|
|
|
let my_claims = Claims {
|
|
|
|
sub: "b@b.com".to_string(),
|
|
|
|
company: "ACME".to_string(),
|
|
|
|
exp: Utc::now().timestamp() + 10000,
|
|
|
|
};
|
|
|
|
let privkey = include_bytes!("private_ecdsa_key.pk8");
|
2019-05-15 10:20:25 -04:00
|
|
|
let token =
|
2019-06-16 11:51:43 -04:00
|
|
|
encode(&Header::new(Algorithm::ES256), &my_claims, Key::Pkcs8(&privkey[..])).unwrap();
|
2019-01-31 23:11:20 -05:00
|
|
|
let pubkey = include_bytes!("public_ecdsa_key.pk8");
|
2019-06-16 12:00:00 -04:00
|
|
|
let token_data =
|
|
|
|
decode::<Claims>(&token, Key::Pkcs8(pubkey), &Validation::new(Algorithm::ES256)).unwrap();
|
2019-01-31 23:11:20 -05:00
|
|
|
assert_eq!(my_claims, token_data.claims);
|
|
|
|
assert!(token_data.header.kid.is_none());
|
|
|
|
}
|
2019-05-15 10:20:25 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[should_panic(expected = "InvalidKeyFormat")]
|
|
|
|
fn fails_with_non_pkcs8_key_format() {
|
|
|
|
let privkey = include_bytes!("private_rsa_key.der");
|
2019-06-16 11:51:43 -04:00
|
|
|
let _encrypted = sign("hello world", Key::Der(&privkey[..]), Algorithm::ES256).unwrap();
|
2019-05-15 10:20:25 -04:00
|
|
|
}
|