Compact JWT implementation in Rust

Build Status License: Apache-2.0 rust 1.60+ required no_std supported

Documentation: Docs.rs crate docs (master)

Minimalistic JSON web token (JWT) implementation with focus on type safety and secure cryptographic primitives.

Usage

Add this to your Crate.toml:

toml [dependencies] jwt-compact = "0.6.0"

Basic token lifecycle

```rust 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 timeoptions = TimeOptions::default(); // Create a symmetric HMAC key, which will be used both to create and verify tokens. let key = Hs256Key::new(b"supersecretkeydonutsteel"); // Create a token. let header = Header::default().withkeyid("my-key"); let claims = Claims::new(CustomClaims { subject: "alice".toowned() }) .setdurationandissuance(&timeoptions, Duration::hours(1)) .setnotbefore(Utc::now()); let tokenstring = Hs256.token(header, &claims, &key)?; println!("token: {}", tokenstring);

// Parse the token. let token = UntrustedToken::new(&tokenstring)?; // Before verifying the token, we might find the key which has signed the token // using the Header.key_id field. asserteq!(token.header().keyid.asderef(), Some("my-key")); // Validate the token integrity. let token: Token = Hs256.validateintegrity(&token, &key)?; // Validate additional conditions. token.claims() .validateexpiration(&timeoptions)? .validatematurity(&time_options)?; Ok::<_, anyhow::Error>(()) ```

See the crate docs for more examples of usage.

Features

Missing features

Alternatives

[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).

See also

License

Licensed under the Apache-2.0 license.