commit
89fbd8f0ce
|
@ -1,5 +1,11 @@
|
|||
# Changelog
|
||||
|
||||
## 6.0.0 (2019-04-21)
|
||||
|
||||
- Update Ring to 0.14
|
||||
- Remove `iat` check to match the JWT spec
|
||||
- Add ES256 and ES384 signing decoding
|
||||
|
||||
## 5.0.1 (2018-09-10)
|
||||
|
||||
- Add implementation of FromStr for Algorithm
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "jsonwebtoken"
|
||||
version = "5.0.1"
|
||||
version = "6.0.0"
|
||||
authors = ["Vincent Prouillet <prouillet.vincent@gmail.com>"]
|
||||
license = "MIT"
|
||||
readme = "README.md"
|
||||
|
@ -13,7 +13,7 @@ keywords = ["jwt", "web", "api", "token", "json"]
|
|||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
serde = "1.0"
|
||||
ring = { version = "0.13", features = ["rsa_signing", "dev_urandom_fallback"] }
|
||||
base64 = "0.9"
|
||||
ring = "0.14.4"
|
||||
base64 = "0.10"
|
||||
untrusted = "0.6"
|
||||
chrono = "0.4"
|
||||
|
|
17
README.md
17
README.md
|
@ -8,11 +8,20 @@
|
|||
Add the following to Cargo.toml:
|
||||
|
||||
```toml
|
||||
jsonwebtoken = "5"
|
||||
jsonwebtoken = "6"
|
||||
serde_derive = "1"
|
||||
serde = "1"
|
||||
```
|
||||
|
||||
## Help wanted for v7
|
||||
|
||||
v6 was released as a stopgap version to update Ring and add a couple of features like ES256/384.
|
||||
The results are not very ergonomic once we factor in all the possible ways to load a RSA key for example.
|
||||
A possible solution is to have decoder types as described in https://github.com/Keats/jsonwebtoken/issues/76
|
||||
but I currently do not have the time to implement it myself.
|
||||
I will take any better idea as well of course!
|
||||
|
||||
|
||||
## How to use
|
||||
Complete examples are available in the examples directory: a basic one and one with a custom header.
|
||||
|
||||
|
@ -72,7 +81,7 @@ let header = decode_header(&token)?;
|
|||
This does not perform any validation on the token.
|
||||
|
||||
#### Validation
|
||||
This library validates automatically the `iat`, `exp` and `nbf` claims if present. You can also validate the `sub`, `iss` and `aud` but
|
||||
This library validates automatically the `exp` and `nbf` claims if present. You can also validate the `sub`, `iss` and `aud` but
|
||||
those require setting the expected value in the `Validation` struct.
|
||||
|
||||
Since validating time fields is always a bit tricky due to clock skew,
|
||||
|
@ -87,7 +96,7 @@ use jsonwebtoken::{Validation, Algorithm};
|
|||
let validation = Validation::default();
|
||||
// Quick way to setup a validation where only the algorithm changes
|
||||
let validation = Validation::new(Algorithm::HS512);
|
||||
// Adding some leeway (in seconds) for iat, exp and nbf checks
|
||||
// Adding some leeway (in seconds) for exp and nbf checks
|
||||
let mut validation = Validation {leeway: 60, ..Default::default()};
|
||||
// Checking issuer
|
||||
let mut validation = Validation {iss: Some("issuer".to_string()), ..Default::default()};
|
||||
|
@ -106,6 +115,8 @@ This library currently supports the following:
|
|||
- RS256
|
||||
- RS384
|
||||
- RS512
|
||||
- ES256
|
||||
- ES384
|
||||
|
||||
### RSA
|
||||
`jsonwebtoken` can only read DER encoded keys currently. If you have openssl installed,
|
||||
|
|
|
@ -18,6 +18,12 @@ pub enum Algorithm {
|
|||
/// HMAC using SHA-512
|
||||
HS512,
|
||||
|
||||
/// ECDSA using SHA-256
|
||||
ES256,
|
||||
|
||||
/// ECDSA using SHA-384
|
||||
ES384,
|
||||
|
||||
/// RSASSA-PKCS1-v1_5 using SHA-256
|
||||
RS256,
|
||||
/// RSASSA-PKCS1-v1_5 using SHA-384
|
||||
|
@ -39,6 +45,8 @@ impl FromStr for Algorithm {
|
|||
"HS256" => Ok(Algorithm::HS256),
|
||||
"HS384" => Ok(Algorithm::HS384),
|
||||
"HS512" => Ok(Algorithm::HS512),
|
||||
"ES256" => Ok(Algorithm::ES256),
|
||||
"ES384" => Ok(Algorithm::ES384),
|
||||
"RS256" => Ok(Algorithm::HS256),
|
||||
"RS384" => Ok(Algorithm::HS384),
|
||||
"RS512" => Ok(Algorithm::HS512),
|
||||
|
@ -55,26 +63,25 @@ fn sign_hmac(alg: &'static digest::Algorithm, key: &[u8], signing_input: &str) -
|
|||
Ok(base64::encode_config::<hmac::Signature>(&digest, base64::URL_SAFE_NO_PAD))
|
||||
}
|
||||
|
||||
/// The actual ECDSA signing + encoding
|
||||
fn sign_ecdsa(alg: &'static signature::EcdsaSigningAlgorithm, key: &[u8], signing_input: &str) -> Result<String> {
|
||||
let signing_key = signature::EcdsaKeyPair::from_pkcs8(alg, untrusted::Input::from(key))?;
|
||||
let rng = rand::SystemRandom::new();
|
||||
let sig = signing_key.sign(&rng, untrusted::Input::from(signing_input.as_bytes()))?;
|
||||
Ok(base64::encode_config(&sig, base64::URL_SAFE_NO_PAD))
|
||||
}
|
||||
|
||||
/// The actual RSA signing + encoding
|
||||
/// Taken from Ring doc https://briansmith.org/rustdoc/ring/signature/index.html
|
||||
fn sign_rsa(alg: Algorithm, key: &[u8], signing_input: &str) -> Result<String> {
|
||||
let ring_alg = match alg {
|
||||
Algorithm::RS256 => &signature::RSA_PKCS1_SHA256,
|
||||
Algorithm::RS384 => &signature::RSA_PKCS1_SHA384,
|
||||
Algorithm::RS512 => &signature::RSA_PKCS1_SHA512,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
fn sign_rsa(alg: &'static signature::RsaEncoding, key: &[u8], signing_input: &str) -> Result<String> {
|
||||
let key_pair = Arc::new(
|
||||
signature::RSAKeyPair::from_der(untrusted::Input::from(key))
|
||||
signature::RsaKeyPair::from_der(untrusted::Input::from(key))
|
||||
.map_err(|_| ErrorKind::InvalidRsaKey)?,
|
||||
);
|
||||
let mut signing_state =
|
||||
signature::RSASigningState::new(key_pair).map_err(|_| ErrorKind::InvalidRsaKey)?;
|
||||
let mut signature = vec![0; signing_state.key_pair().public_modulus_len()];
|
||||
let mut signature = vec![0; key_pair.public_modulus_len()];
|
||||
let rng = rand::SystemRandom::new();
|
||||
signing_state
|
||||
.sign(ring_alg, &rng, signing_input.as_bytes(), &mut signature)
|
||||
key_pair
|
||||
.sign(alg, &rng, signing_input.as_bytes(), &mut signature)
|
||||
.map_err(|_| ErrorKind::InvalidRsaKey)?;
|
||||
|
||||
Ok(base64::encode_config::<[u8]>(&signature, base64::URL_SAFE_NO_PAD))
|
||||
|
@ -90,15 +97,18 @@ pub fn sign(signing_input: &str, key: &[u8], algorithm: Algorithm) -> Result<Str
|
|||
Algorithm::HS384 => sign_hmac(&digest::SHA384, key, signing_input),
|
||||
Algorithm::HS512 => sign_hmac(&digest::SHA512, key, signing_input),
|
||||
|
||||
Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 => {
|
||||
sign_rsa(algorithm, key, signing_input)
|
||||
}
|
||||
Algorithm::ES256 => sign_ecdsa(&signature::ECDSA_P256_SHA256_FIXED_SIGNING, key, signing_input),
|
||||
Algorithm::ES384 => sign_ecdsa(&signature::ECDSA_P384_SHA384_FIXED_SIGNING, key, signing_input),
|
||||
|
||||
Algorithm::RS256 => sign_rsa(&signature::RSA_PKCS1_SHA256, key, signing_input),
|
||||
Algorithm::RS384 => sign_rsa(&signature::RSA_PKCS1_SHA384, key, signing_input),
|
||||
Algorithm::RS512 => sign_rsa(&signature::RSA_PKCS1_SHA512, key, signing_input),
|
||||
}
|
||||
}
|
||||
|
||||
/// See Ring RSA docs for more details
|
||||
fn verify_rsa(
|
||||
alg: &signature::RSAParameters,
|
||||
/// See Ring docs for more details
|
||||
fn verify_ring(
|
||||
alg: &dyn signature::VerificationAlgorithm,
|
||||
signature: &str,
|
||||
signing_input: &str,
|
||||
key: &[u8],
|
||||
|
@ -133,14 +143,20 @@ pub fn verify(
|
|||
let signed = sign(signing_input, key, algorithm)?;
|
||||
Ok(verify_slices_are_equal(signature.as_ref(), signed.as_ref()).is_ok())
|
||||
}
|
||||
Algorithm::ES256 => {
|
||||
verify_ring(&signature::ECDSA_P256_SHA256_FIXED, signature, signing_input, key)
|
||||
}
|
||||
Algorithm::ES384 => {
|
||||
verify_ring(&signature::ECDSA_P384_SHA384_FIXED, signature, signing_input, key)
|
||||
}
|
||||
Algorithm::RS256 => {
|
||||
verify_rsa(&signature::RSA_PKCS1_2048_8192_SHA256, signature, signing_input, key)
|
||||
verify_ring(&signature::RSA_PKCS1_2048_8192_SHA256, signature, signing_input, key)
|
||||
}
|
||||
Algorithm::RS384 => {
|
||||
verify_rsa(&signature::RSA_PKCS1_2048_8192_SHA384, signature, signing_input, key)
|
||||
verify_ring(&signature::RSA_PKCS1_2048_8192_SHA384, signature, signing_input, key)
|
||||
}
|
||||
Algorithm::RS512 => {
|
||||
verify_rsa(&signature::RSA_PKCS1_2048_8192_SHA512, signature, signing_input, key)
|
||||
verify_ring(&signature::RSA_PKCS1_2048_8192_SHA512, signature, signing_input, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -36,6 +36,8 @@ pub enum ErrorKind {
|
|||
InvalidToken,
|
||||
/// When the signature doesn't match
|
||||
InvalidSignature,
|
||||
/// When the secret given is not a valid ECDSA key
|
||||
InvalidEcdsaKey,
|
||||
/// When the secret given is not a valid RSA key
|
||||
InvalidRsaKey,
|
||||
/// When the algorithm from string doesn't match the one passed to `from_str`
|
||||
|
@ -50,8 +52,6 @@ pub enum ErrorKind {
|
|||
InvalidAudience,
|
||||
/// When a token’s `aud` claim does not match one of the expected audience values
|
||||
InvalidSubject,
|
||||
/// When a token’s `iat` claim is in the future
|
||||
InvalidIssuedAt,
|
||||
/// When a token’s nbf claim represents a time in the future
|
||||
ImmatureSignature,
|
||||
/// When the algorithm in the header doesn't match the one passed to `decode`
|
||||
|
@ -64,6 +64,8 @@ pub enum ErrorKind {
|
|||
Json(serde_json::Error),
|
||||
/// Some of the text was invalid UTF-8
|
||||
Utf8(::std::string::FromUtf8Error),
|
||||
/// Something unspecified went wrong with crypto
|
||||
Crypto(::ring::error::Unspecified),
|
||||
|
||||
/// Hints that destructuring should not be exhaustive.
|
||||
///
|
||||
|
@ -79,17 +81,18 @@ impl StdError for Error {
|
|||
match *self.0 {
|
||||
ErrorKind::InvalidToken => "invalid token",
|
||||
ErrorKind::InvalidSignature => "invalid signature",
|
||||
ErrorKind::InvalidEcdsaKey => "invalid ECDSA key",
|
||||
ErrorKind::InvalidRsaKey => "invalid RSA key",
|
||||
ErrorKind::ExpiredSignature => "expired signature",
|
||||
ErrorKind::InvalidIssuer => "invalid issuer",
|
||||
ErrorKind::InvalidAudience => "invalid audience",
|
||||
ErrorKind::InvalidSubject => "invalid subject",
|
||||
ErrorKind::InvalidIssuedAt => "invalid issued at",
|
||||
ErrorKind::ImmatureSignature => "immature signature",
|
||||
ErrorKind::InvalidAlgorithm => "algorithms don't match",
|
||||
ErrorKind::Base64(ref err) => err.description(),
|
||||
ErrorKind::Json(ref err) => err.description(),
|
||||
ErrorKind::Utf8(ref err) => err.description(),
|
||||
ErrorKind::Crypto(ref err) => err.description(),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
@ -98,17 +101,18 @@ impl StdError for Error {
|
|||
match *self.0 {
|
||||
ErrorKind::InvalidToken => None,
|
||||
ErrorKind::InvalidSignature => None,
|
||||
ErrorKind::InvalidEcdsaKey => None,
|
||||
ErrorKind::InvalidRsaKey => None,
|
||||
ErrorKind::ExpiredSignature => None,
|
||||
ErrorKind::InvalidIssuer => None,
|
||||
ErrorKind::InvalidAudience => None,
|
||||
ErrorKind::InvalidSubject => None,
|
||||
ErrorKind::InvalidIssuedAt => None,
|
||||
ErrorKind::ImmatureSignature => None,
|
||||
ErrorKind::InvalidAlgorithm => None,
|
||||
ErrorKind::Base64(ref err) => Some(err),
|
||||
ErrorKind::Json(ref err) => Some(err),
|
||||
ErrorKind::Utf8(ref err) => Some(err),
|
||||
ErrorKind::Crypto(ref err) => Some(err),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
@ -119,17 +123,18 @@ impl fmt::Display for Error {
|
|||
match *self.0 {
|
||||
ErrorKind::InvalidToken => write!(f, "invalid token"),
|
||||
ErrorKind::InvalidSignature => write!(f, "invalid signature"),
|
||||
ErrorKind::InvalidEcdsaKey => write!(f, "invalid ECDSA key"),
|
||||
ErrorKind::InvalidRsaKey => write!(f, "invalid RSA key"),
|
||||
ErrorKind::ExpiredSignature => write!(f, "expired signature"),
|
||||
ErrorKind::InvalidIssuer => write!(f, "invalid issuer"),
|
||||
ErrorKind::InvalidAudience => write!(f, "invalid audience"),
|
||||
ErrorKind::InvalidSubject => write!(f, "invalid subject"),
|
||||
ErrorKind::InvalidIssuedAt => write!(f, "invalid issued at"),
|
||||
ErrorKind::ImmatureSignature => write!(f, "immature signature"),
|
||||
ErrorKind::InvalidAlgorithm => write!(f, "algorithms don't match"),
|
||||
ErrorKind::Base64(ref err) => write!(f, "base64 error: {}", err),
|
||||
ErrorKind::Json(ref err) => write!(f, "JSON error: {}", err),
|
||||
ErrorKind::Utf8(ref err) => write!(f, "UTF-8 error: {}", err),
|
||||
ErrorKind::Crypto(ref err) => write!(f, "Crypto error: {}", err),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
@ -153,6 +158,18 @@ impl From<::std::string::FromUtf8Error> for Error {
|
|||
}
|
||||
}
|
||||
|
||||
impl From<::ring::error::Unspecified> for Error {
|
||||
fn from(err: ::ring::error::Unspecified) -> Error {
|
||||
new_error(ErrorKind::Crypto(err))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<::ring::error::KeyRejected> for Error {
|
||||
fn from(_err: ::ring::error::KeyRejected) -> Error {
|
||||
new_error(ErrorKind::InvalidEcdsaKey)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ErrorKind> for Error {
|
||||
fn from(kind: ErrorKind) -> Error {
|
||||
new_error(kind)
|
||||
|
|
|
@ -37,17 +37,11 @@ pub struct Validation {
|
|||
///
|
||||
/// Defaults to `true`.
|
||||
pub validate_exp: bool,
|
||||
/// Whether to validate the `iat` field.
|
||||
///
|
||||
/// It will return an error if the time in the `iat` field is in the future.
|
||||
///
|
||||
/// Defaults to `true`.
|
||||
pub validate_iat: bool,
|
||||
/// Whether to validate the `nbf` field.
|
||||
///
|
||||
/// It will return an error if the current timestamp is before the time in the `nbf` field.
|
||||
///
|
||||
/// Defaults to `true`.
|
||||
/// Defaults to `false`.
|
||||
pub validate_nbf: bool,
|
||||
/// If it contains a value, the validation will check that the `aud` field is the same as the
|
||||
/// one provided and will error otherwise.
|
||||
|
@ -94,7 +88,6 @@ impl Default for Validation {
|
|||
leeway: 0,
|
||||
|
||||
validate_exp: true,
|
||||
validate_iat: false,
|
||||
validate_nbf: false,
|
||||
|
||||
iss: None,
|
||||
|
@ -109,16 +102,6 @@ impl Default for Validation {
|
|||
pub fn validate(claims: &Map<String, Value>, options: &Validation) -> Result<()> {
|
||||
let now = Utc::now().timestamp();
|
||||
|
||||
if options.validate_iat {
|
||||
if let Some(iat) = claims.get("iat") {
|
||||
if from_value::<i64>(iat.clone())? > now + options.leeway {
|
||||
return Err(new_error(ErrorKind::InvalidIssuedAt));
|
||||
}
|
||||
} else {
|
||||
return Err(new_error(ErrorKind::InvalidIssuedAt));
|
||||
}
|
||||
}
|
||||
|
||||
if options.validate_exp {
|
||||
if let Some(exp) = claims.get("exp") {
|
||||
if from_value::<i64>(exp.clone())? < now - options.leeway {
|
||||
|
@ -182,45 +165,6 @@ mod tests {
|
|||
|
||||
use errors::ErrorKind;
|
||||
|
||||
#[test]
|
||||
fn iat_in_past_ok() {
|
||||
let mut claims = Map::new();
|
||||
claims.insert("iat".to_string(), to_value(Utc::now().timestamp() - 10000).unwrap());
|
||||
let validation =
|
||||
Validation { validate_exp: false, validate_iat: true, ..Validation::default() };
|
||||
let res = validate(&claims, &validation);
|
||||
assert!(res.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iat_in_future_fails() {
|
||||
let mut claims = Map::new();
|
||||
claims.insert("iat".to_string(), to_value(Utc::now().timestamp() + 100000).unwrap());
|
||||
let validation =
|
||||
Validation { validate_exp: false, validate_iat: true, ..Validation::default() };
|
||||
let res = validate(&claims, &validation);
|
||||
assert!(res.is_err());
|
||||
|
||||
match res.unwrap_err().kind() {
|
||||
&ErrorKind::InvalidIssuedAt => (),
|
||||
_ => assert!(false),
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iat_in_future_but_in_leeway_ok() {
|
||||
let mut claims = Map::new();
|
||||
claims.insert("iat".to_string(), to_value(Utc::now().timestamp() + 50).unwrap());
|
||||
let validation = Validation {
|
||||
leeway: 1000 * 60,
|
||||
validate_iat: true,
|
||||
validate_exp: false,
|
||||
..Default::default()
|
||||
};
|
||||
let res = validate(&claims, &validation);
|
||||
assert!(res.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exp_in_future_ok() {
|
||||
let mut claims = Map::new();
|
||||
|
|
|
@ -0,0 +1,38 @@
|
|||
extern crate jsonwebtoken;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
extern crate chrono;
|
||||
|
||||
use chrono::Utc;
|
||||
use jsonwebtoken::{decode, encode, sign, verify, Algorithm, Header, Validation};
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
|
||||
struct Claims {
|
||||
sub: String,
|
||||
company: String,
|
||||
exp: i64,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_sign_verification() {
|
||||
let privkey = include_bytes!("private_ecdsa_key.pk8");
|
||||
let encrypted = sign("hello world", privkey, Algorithm::ES256).unwrap();
|
||||
let pubkey = include_bytes!("public_ecdsa_key.pk8");
|
||||
let is_valid = verify(&encrypted, "hello world", pubkey, Algorithm::ES256).unwrap();
|
||||
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");
|
||||
let token = encode(&Header::new(Algorithm::ES256), &my_claims, privkey).unwrap();
|
||||
let pubkey = include_bytes!("public_ecdsa_key.pk8");
|
||||
let token_data = decode::<Claims>(&token, pubkey, &Validation::new(Algorithm::ES256)).unwrap();
|
||||
assert_eq!(my_claims, token_data.claims);
|
||||
assert!(token_data.header.kid.is_none());
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1 @@
|
|||
ò@¡Oà%¶I½_³ëÔ÷!I«AM÷<>ÄLïÃüyÁ5+\°I†¬Îô¾w¢[¨
µa <09>Ô«xG2ÉGU¾
|
Loading…
Reference in New Issue