jsonwebtoken

repository·master·Indexed 24 days ago

https://github.com/keats/jsonwebtoken

A Rust library for creating and parsing JSON Web Tokens (JWT) and JSON Web Signatures (JWS) in a strongly typed way. It supports various signing algorithms across Hmac, Rsa, Ec, and Ed families. The library decouples cryptography logic via a CryptoProvider, with built-in support for aws-lc-rs and Rust Crypto. It provides tools for encoding, decoding, and validating tokens, as well as support for JWK (JSON Web Key) and PEM/DER encoded keys.

Tokens
6.6K
Snippets
11
Records
41
Agent score
84%

What's inside jsonwebtoken

  1. Select a cryptography backend via CryptoProvider

    master

    The jsonwebtoken crate decouples its cryptography logic behind the CryptoProvider struct. You must ensure a provider is available for the library to function.

    There are two built-in options available via Cargo features:

    1. aws_lc_rs: Uses the aws-lc-rs crate (requires the aws_lc_rs feature).
    2. rust_crypto: Uses crates from the Rust Crypto project (requires the rust_crypto feature).

    If you have enabled exactly one of these features, the library will automatically select the corresponding DEFAULT_PROVIDER. If you need to use a custom implementation or if automatic selection fails, you must manually install a provider using CryptoProvider::install_default() before performing any signing or verification operations.

  2. How Validation handles time-based claims (exp and nbf)

    master

    The Validation struct manages time-based verification using UTC timestamps in seconds.

    • exp (Expiration Time): If validate_exp is true, the token is rejected if the current time is past the exp value (adjusted by leeway).
    • nbf (Not Before): If validate_nbf is true, the token is rejected if the current time is before the nbf value (adjusted by leeway).
    • leeway: A buffer in seconds applied to both exp and nbf to account for clock skew between servers.
    • reject_tokens_expiring_in_less_than: A security setting that rejects tokens if they are set to expire within this many seconds from the current time, preventing expiration during network transit.
  3. Core JWT operations: Encoding and Decoding

    master

    The jsonwebtoken crate provides high-level functions for creating and verifying JSON Web Tokens.

    • Encoding: Use encode to create a JWT. This requires an EncodingKey, a Header, and the claims you wish to include.
    • Decoding: Use decode to verify and parse a JWT. This requires a DecodingKey, a Validation configuration, and the token string. It returns TokenData<T>, where T is your claims structure.
    • Header Inspection: Use decode_header if you need to inspect the JWT header (e.g., to determine the algorithm) without verifying the signature.
  4. Use encryption and compression in JWT headers

    master

    The Header struct supports the enc (encryption) and zip (compression) fields for JWE (JSON Web Encryption) and compressed payloads.

    Encryption (enc)

    The Enc enum defines encryption algorithms for encrypted payloads (RFC 7518). Supported variants include:

    • Enc::A128CBC_HS256
    • Enc::A192CBC_HS384
    • Enc::A256CBC_HS512
    • Enc::A128GCM
    • Enc::A192GCM
    • Enc::A256GCM
    • Enc::Other(String) for custom algorithms.

    Compression (zip)

    The Zip enum defines compression applied to the plaintext (RFC 7516). Supported variants include:

    • Zip::Deflate
    • Zip::Other(String) for custom compression methods.
  5. Group algorithms by AlgorithmFamily

    master
    The AlgorithmFamily enum categorizes algorithms into broader cryptographic families (Hmac, Rsa, Ec, Ed). You can use Algorithm::family(self) to determine which family a specific algorithm belongs to, or AlgorithmFamily::algorithms() to retrieve a list of all supported algorithms within that family.
  6. Manually install a default CryptoProvider

    master

    If the library cannot automatically determine the provider from crate features, or if you wish to use a custom implementation, call install_default with a reference to your chosen CryptoProvider. This can be called successfully at most once per process execution.

    To use a built-in provider manually, you can use crypto::aws_lc::DEFAULT_PROVIDER or crypto::rust_crypto::DEFAULT_PROVIDER depending on which feature is enabled.

  7. Encode and Decode JWS

    master

    JSON Web Signature (JWS) is handled similarly to JWT using the jsonwebtoken::jws module.

    use jsonwebtoken::jws::{encode, decode};
    
    let encoded = encode(&Header::default(), &my_claims, &EncodingKey::from_secret("secret".as_ref()))?;
    // decode returns a struct where you can access the .claims field
    let decoded_claims = decode(&encoded, &DecodingKey::from_secret("secret".as_ref()), &Validation::default())?.claims;

    jsonwebtoken::jws::encode returns a Jws<C> struct. The generic parameter C represents the claims type, which provides type safety when nesting JWS objects within other structures.

    use jsonwebtoken::jws::{encode, decode};
    
    let encoded = encode(&Header::default(), &my_claims, &EncodingKey::from_secret("secret".as_ref()))?;
    my_claims = decode(&encoded, &DecodingKey::from_secret("secret".as_ref()), &Validation::default())?.claims;
  8. Configure a custom `CryptoProvider`

    master

    A CryptoProvider allows you to inject custom logic for signing, verifying, and JWK (JSON Web Key) processing. It is composed of:

    • signer_factory: A function that produces a Box<dyn JwtSigner> for a given Algorithm and EncodingKey.
    • verifier_factory: A function that produces a Box<dyn JwtVerifier> for a given Algorithm and DecodingKey.
    • key_utils: A KeyUtils struct containing function pointers for JWK-related operations like extracting RSA/EC/ED components or computing digests.
  9. Configure JWT validation with the Validation struct

    master

    The Validation struct defines the rules for verifying a JWT's claims and signature after decoding. You can create a default validation setup using Validation::new(alg) or Validation::new_for_family(family).

    Key configuration options include:

    • leeway: Seconds added to exp and nbf validation to account for clock skew (default: 60).
    • required_spec_claims: A set of claims that MUST be present in the token (exp, nbf, aud, iss, sub).
    • validate_exp, validate_nbf, validate_aud: Boolean flags to enable/disable specific claim checks.
    • algorithms: A list of allowed Algorithm types.
    use jsonwebtoken::{Validation, Algorithm};
    
    let mut validation = Validation::new(Algorithm::HS256);
    validation.leeway = 5;
    // Setting audience
    validation.set_audience(&["Me"]); // a single string
    validation.set_audience(&["Me", "You"]); // array of strings
    // or issuer
    validation.set_issuer(&["Me"]); // a single string
    validation.set_issuer(&["Me", "You"]); // array of strings
    // Setting required claims
    validation.set_required_spec_claims(&["exp", "iss", "aud"]);
  10. Add custom fields to a JWT Header

    master
    The Header struct includes an extras field of type Extras that allows you to add non-standard, custom header fields. These fields are flattened into the root level of the header JSON when serialized. Use extras.insert(key, value) to add fields and extras.get(key) to retrieve them.
  11. Set required audience, issuer, and spec claims

    master

    Use the following methods to configure specific claim requirements on a Validation instance:

    • set_audience<T: ToString>(&mut self, items: &[T]): Sets the acceptable audience members. Validation succeeds if the token's aud claim is a member of this set.
    • set_issuer<T: ToString>(&mut self, items: &[T]): Sets the acceptable issuers. Validation succeeds if the token's iss claim is a member of this set.
    • set_required_spec_claims<T: ToString>(&mut self, items: &[T]): Defines which standard claims (exp, nbf, aud, iss, sub) must be present in the token for it to be considered valid.