Compact JWT implementation in Rust
APACHE-2.0 License
Documentation:
Minimalistic JSON web token (JWT) implementation with focus on type safety and secure cryptographic primitives.
Add this to your Crate.toml
:
[dependencies]
jwt-compact = "0.9.0-beta.1"
use chrono::{Duration, Utc};
use jwt_compact::{prelude::*, alg::{Hs256, Hs256Key}};
use serde::{Serialize, Deserialize};
/// Custom claims encoded in the token.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct CustomClaims {
#[serde(rename = "sub")]
subject: String,
// other fields...
}
// Choose time-related options for token creation / validation.
let time_options = TimeOptions::default();
// Create a symmetric HMAC key, which will be used both to create and verify tokens.
let key = Hs256Key::new(b"super_secret_key_donut_steel");
// Create a token.
let header = Header::empty().with_key_id("my-key");
let claims = Claims::new(CustomClaims { subject: "alice".to_owned() })
.set_duration_and_issuance(&time_options, Duration::hours(1))
.set_not_before(Utc::now());
let token_string = Hs256.token(&header, &claims, &key)?;
println!("token: {token_string}");
// Parse the token.
let token = UntrustedToken::new(&token_string)?;
// Before verifying the token, we might find the key which has signed the token
// using the `Header.key_id` field.
assert_eq!(token.header().key_id.as_deref(), Some("my-key"));
// Validate the token integrity.
let token: Token<CustomClaims> = Hs256.validator(&key).validate(&token)?;
// Validate additional conditions.
token.claims()
.validate_expiration(&time_options)?
.validate_maturity(&time_options)?;
Ok::<_, anyhow::Error>(())
See the crate docs for more examples of usage.
HS256
, HS384
and HS512
algorithms are implemented via pure Rust sha2
crate.EdDSA
algorithm with the Ed25519 elliptic curve, and ES256K
algorithmES*
algorithms).ES256
algorithm is supported via pure Rust p256
crate.RS*
and PS*
) are supported via pure Rust rsa
crate.rsa
crate (along with other RSA implementations) may be susceptible tono_std
mode. No-std supportiss
– the token issuer).iss
may be a human-readable short ID,ES384
and ES512
algorithms.jsonwebtoken
, frank_jwt
or biscuit
may be viable alternatives depending on the use case
(e.g., none of them seems to implement EdDSA
or ES256K
algorithms).
All contributions are welcome! See the contributing guide to help you get involved.
Licensed under the Apache-2.0 license.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in jwt-compact
by you, as defined in the Apache-2.0 license,
shall be licensed as above, without any additional terms or conditions.