jsonwebtoken/tests/rsa.rs

68 lines
1.8 KiB
Rust
Raw Normal View History

2017-02-22 02:45:28 -05:00
extern crate jsonwebtoken;
#[macro_use]
extern crate serde_derive;
extern crate chrono;
2017-02-22 02:45:28 -05:00
use chrono::Utc;
2019-06-16 12:00:00 -04:00
use jsonwebtoken::{decode, encode, sign, verify, Algorithm, Header, Key, Validation};
2017-02-22 02:45:28 -05:00
const RSA_ALGORITHMS: &[Algorithm] = &[
Algorithm::RS256,
Algorithm::RS384,
Algorithm::RS512,
Algorithm::PS256,
Algorithm::PS384,
Algorithm::PS512,
];
2017-02-22 02:45:28 -05:00
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
2019-07-06 14:36:32 -04:00
pub struct Claims {
2017-02-22 02:45:28 -05:00
sub: String,
company: String,
exp: i64,
2017-02-22 02:45:28 -05:00
}
2017-04-10 23:40:01 -04:00
#[test]
fn round_trip_sign_verification() {
2019-05-15 10:20:25 -04:00
let privkey = include_bytes!("private_rsa_key.der");
for &alg in RSA_ALGORITHMS {
2019-06-16 12:00:00 -04:00
let encrypted = sign("hello world", Key::Der(&privkey[..]), alg).unwrap();
let is_valid =
2019-06-16 12:00:00 -04:00
verify(&encrypted, "hello world", Key::Der(include_bytes!("public_rsa_key.der")), alg)
.unwrap();
assert!(is_valid);
}
2017-04-10 23:40:01 -04:00
}
2017-02-22 02:45:28 -05:00
#[test]
fn round_trip_claim() {
let my_claims = Claims {
sub: "b@b.com".to_string(),
company: "ACME".to_string(),
exp: Utc::now().timestamp() + 10000,
2017-02-22 02:45:28 -05:00
};
2019-05-15 10:20:25 -04:00
let privkey = include_bytes!("private_rsa_key.der");
2019-06-16 12:00:00 -04:00
for &alg in RSA_ALGORITHMS {
2019-06-16 12:00:00 -04:00
let token = encode(&Header::new(alg), &my_claims, Key::Der(&privkey[..])).unwrap();
let token_data = decode::<Claims>(
&token,
Key::Der(include_bytes!("public_rsa_key.der")),
&Validation::new(alg),
)
.unwrap();
assert_eq!(my_claims, token_data.claims);
assert!(token_data.header.kid.is_none());
}
2017-02-22 02:45:28 -05:00
}
2019-05-15 10:20:25 -04:00
#[test]
#[should_panic(expected = "InvalidRsaKey")]
fn fails_with_different_key_format() {
let privkey = include_bytes!("private_rsa_key.der");
2019-06-16 11:51:43 -04:00
sign("hello world", Key::Pkcs8(&privkey[..]), Algorithm::RS256).unwrap();
2019-05-15 10:20:25 -04:00
}
2019-07-06 14:36:32 -04:00
#[test]
fn can_decode_jwt_io_example() {}