### Install jsonwebtoken with rust_crypto backend Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Alternative TOML entry for installing the jsonwebtoken crate with the rust_crypto backend. ```toml jsonwebtoken = { version = "10", features = ["rust_crypto"] } ``` -------------------------------- ### Rust JWT Encoding Example Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/encoding.md Example demonstrating how to encode and sign a JWT using the `encode` function with HS256 algorithm. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{encode, Header, EncodingKey, Algorithm}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, company: String, exp: u64, } let my_claims = Claims { sub: "b@b.com".to_owned(), company: "ACME".to_owned(), exp: 10000000000, }; let mut header = Header::new(Algorithm::HS256); let key = EncodingKey::from_secret(b"secret"); let token = encode(&header, &my_claims, &key).unwrap(); println!("{}", token); ``` -------------------------------- ### Install Custom CryptoProvider Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md If no crypto feature is enabled, a custom `CryptoProvider` must be implemented and installed before using encoding/decoding operations. The provider should only be installed once. ```rust use jsonwebtoken::crypto::CryptoProvider; let my_provider = /* your implementation */; my_provider.install_default().expect("Should only install once"); ``` -------------------------------- ### Validation::new Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/validation.md Creates a default validation setup that permits a single specified algorithm. ```APIDOC ## Validation::new(alg: Algorithm) ### Description Creates a default validation setup permitting a single algorithm. ### Parameters #### Path Parameters - **alg** (Algorithm) - Required - The allowed signing algorithm ### Returns - **Validation** - A new validation with sensible defaults. ### Defaults Applied - `required_spec_claims`: `{"exp"}` - `leeway`: `60` seconds - `validate_exp`: `true` - `validate_nbf`: `false` - `validate_aud`: `true` - `algorithms`: `vec![alg]` ### Example ```rust use jsonwebtoken::{Validation, Algorithm}; let validation = Validation::new(Algorithm::RS256); ``` ``` -------------------------------- ### Install jsonwebtoken with aws_lc_rs backend Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Add this to your Cargo.toml to include the jsonwebtoken crate with the aws_lc_rs crypto backend. Ensure serde and serde_json are also included. ```toml [dependencies] jsonwebtoken = { version = "10", features = ["aws_lc_rs"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" ``` -------------------------------- ### Install Default CryptoProvider Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/crypto.md Installs a custom CryptoProvider as the default for the process. This function should be called at most once per process execution and before any JWT operations if no default feature is enabled. It returns Ok(()) on success or an error if a default is already installed. ```rust use jsonwebtoken::crypto::CryptoProvider; let provider = my_custom_provider(); provider.install_default() .expect("CryptoProvider should only be installed once"); ``` -------------------------------- ### Implement Custom Crypto Provider Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/crypto.md For advanced scenarios, implement a custom CryptoProvider by defining your own JwtSigner and JwtVerifier. Install it as the default provider before use. ```rust use jsonwebtoken::crypto::{CryptoProvider, JwtSigner, JwtVerifier}; use jsonwebtoken::{Algorithm, EncodingKey, DecodingKey, errors::Result}; // Implement custom signers and verifiers... struct CustomSigner { /* ... */ } impl JwtSigner for CustomSigner { fn algorithm(&self) -> Algorithm { Algorithm::HS256 } } struct CustomVerifier { /* ... */ } impl JwtVerifier for CustomVerifier { fn algorithm(&self) -> Algorithm { Algorithm::HS256 } } // Create provider let my_provider = CryptoProvider { signer_factory: |alg, key| { // Create signer Ok(Box::new(CustomSigner { /* ... */ })) }, verifier_factory: |alg, key| { // Create verifier Ok(Box::new(CustomVerifier { /* ... */ })) }, key_utils: /* ... */, }; // Install as default my_provider.install_default().unwrap(); ``` -------------------------------- ### Complete Validation Configuration Example Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/validation.md Demonstrates how to configure detailed validation rules for decoding JWTs, including audience, issuer, subject, and time-based claims like expiration and not-before, along with leeway for clock skew. ```APIDOC ## Example: Complete Validation Configuration ### Description This example shows how to set up a comprehensive `Validation` object to decode and verify a JWT. It includes configuring audience, issuer, subject, required claims, and leeway for clock synchronization. ### Code ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, aud: String, iss: String, exp: u64, nbf: u64, } let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."; let key = DecodingKey::from_secret(b"secret"); // Configure validation rules let mut validation = Validation::new(Algorithm::HS256); validation.set_audience(&["my-app"]); validation.set_issuer(&["https://auth.example.com"]); validation.sub = Some("user-123".to_string()); validation.validate_nbf = true; validation.leeway = 5; // Allow 5 seconds clock skew validation.set_required_spec_claims(&["exp", "nbf", "iss", "aud", "sub"]); match decode::(token, &key, &validation) { Ok(token_data) => { println!("Valid token for user: {}", token_data.claims.sub); } Err(e) => { eprintln!("Validation failed: {}", e); } } ``` ``` -------------------------------- ### Get Algorithms for RSA Family Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/algorithms.md Demonstrates how to retrieve all supported RSA algorithms using the `algorithms()` method from the `AlgorithmFamily` enum. This is useful for verifying supported algorithms or iterating through them. ```rust use jsonwebtoken::AlgorithmFamily; let rsa_algs = AlgorithmFamily::Rsa.algorithms(); assert!(rsa_algs.contains(&jsonwebtoken::Algorithm::RS256)); assert!(rsa_algs.contains(&jsonwebtoken::Algorithm::PS256)); ``` -------------------------------- ### JWT Decoding Example Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/decoding.md Demonstrates how to decode and validate a JWT using a secret key and basic validation rules. Ensure the `Claims` struct matches the expected payload structure. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, exp: u64, } let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."; let key = DecodingKey::from_secret(b"secret"); let validation = Validation::new(Algorithm::HS256); match decode::(token, &key, &validation) { Ok(data) => println!("Claims: {:?}", data.claims), Err(err) => eprintln!("Decode error: {}", err), } ``` -------------------------------- ### Validation::new_for_family Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/validation.md Creates a default validation setup allowing any algorithm within a specified family. ```APIDOC ## Validation::new_for_family(family: AlgorithmFamily) ### Description Creates a default validation setup allowing any algorithm in the specified family. ### Parameters #### Path Parameters - **family** (AlgorithmFamily) - Required - The algorithm family ### Returns - **Validation** - A validation permitting all algorithms in the family. ### Example ```rust use jsonwebtoken::{Validation, AlgorithmFamily}; // Allow any RSA algorithm: RS256, RS384, RS512, PS256, PS384, PS512 let validation = Validation::new_for_family(AlgorithmFamily::Rsa); ``` ``` -------------------------------- ### Get Algorithms for HMAC Family Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/algorithms.md Demonstrates how to retrieve the count of supported HMAC algorithms using the `algorithms()` method. This can be used to confirm the number of available HS algorithms. ```rust use jsonwebtoken::AlgorithmFamily; let hmac_algs = AlgorithmFamily::Hmac.algorithms(); assert_eq!(hmac_algs.len(), 3); // HS256, HS384, HS512 ``` -------------------------------- ### Create Validation with Single Algorithm Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/validation.md Use `Validation::new` to create a validation setup that permits only a single specified algorithm. Defaults are applied for required claims, leeway, and expiration/not-before/audience validation. ```rust use jsonwebtoken::{Validation, Algorithm}; let validation = Validation::new(Algorithm::RS256); ``` -------------------------------- ### Example: Handling InvalidToken Error Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/errors.md Demonstrates how to use the kind() method to check for specific error types like InvalidToken during JWT decoding. ```rust use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; use jsonwebtoken::errors::ErrorKind; let result = decode::("invalid", &DecodingKey::from_secret(b"key"), &Validation::new(Algorithm::HS256)); if let Err(e) = result { match e.kind() { ErrorKind::InvalidToken => println!("Token format invalid"), _ => println!("Other error"), } } ``` -------------------------------- ### Create Validation for Algorithm Family Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/validation.md Use `Validation::new_for_family` to create a validation setup that allows any algorithm within a specified family, such as RSA or ECDSA. This is useful when you need flexibility in the signing algorithm. ```rust use jsonwebtoken::{Validation, AlgorithmFamily}; // Allow any RSA algorithm: RS256, RS384, RS512, PS256, PS384, PS512 let validation = Validation::new_for_family(AlgorithmFamily::Rsa); ``` -------------------------------- ### Get raw key bytes Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/encoding.md Returns the raw bytes of the key. This is intended for use when defining custom `CryptoProvider` implementations. ```rust pub fn as_bytes(&self) -> &[u8] ``` ```rust let key_bytes = key.as_bytes(); ``` -------------------------------- ### Complete JWT Validation Configuration Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/validation.md Configure detailed validation rules for a JWT, including audience, issuer, subject, expiration, and not-before times. This example also demonstrates setting a leeway for clock skew. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, aud: String, iss: String, exp: u64, nbf: u64, } let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."; let key = DecodingKey::from_secret(b"secret"); // Configure validation rules let mut validation = Validation::new(Algorithm::HS256); validation.set_audience(&["my-app"]); validation.set_issuer(&["https://auth.example.com"]); validation.sub = Some("user-123".to_string()); validation.validate_nbf = true; validation.leeway = 5; // Allow 5 seconds clock skew validation.set_required_spec_claims(&["exp", "nbf", "iss", "aud", "sub"]); match decode::(token, &key, &validation) { Ok(token_data) => { println!("Valid token for user: {}", token_data.claims.sub); } Err(e) => { eprintln!("Validation failed: {}", e); } } ``` -------------------------------- ### Decoding Token with Custom Claims Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Example of decoding a token and obtaining TokenData with a specific UserClaims struct. Ensure the UserClaims struct derives Serialize and Deserialize. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{decode, TokenData}; #[derive(Serialize, Deserialize)] struct UserClaims { user_id: String, email: String, is_admin: bool, } // decode returns TokenData let token_data: TokenData = decode(/*...*/).unwrap(); ``` -------------------------------- ### Decode JWT Claims in Rust Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Example of decoding a JWT into custom claims using the jsonwebtoken crate. Requires serde for serialization and deserialization, and specifies validation parameters. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, exp: u64, } fn main() -> Result<(), Box> { let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."; let key = DecodingKey::from_secret(b"secret"); let validation = Validation::new(Algorithm::HS256); let token_data = decode::(token, &key, &validation)?; println!("Claims: {:?}", token_data.claims); Ok(()) } ``` -------------------------------- ### Get Current Timestamp for JWT Expiration Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/validation.md Use this function to get the current UTC timestamp in seconds, which is essential for setting JWT expiration times. ```rust pub fn get_current_timestamp() -> u64 ``` ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{encode, Header, EncodingKey, get_current_timestamp}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, exp: u64, iat: u64, } let now = get_current_timestamp(); let claims = Claims { sub: "user@example.com".to_string(), exp: now + 3600, // Expires in 1 hour iat: now, }; let token = encode(&Header::default(), &claims, &EncodingKey::from_secret(b"secret")).unwrap(); ``` -------------------------------- ### Get Current Timestamp Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Retrieves the current Unix timestamp in seconds. ```APIDOC ## get_current_timestamp ### Description Retrieves the current Unix timestamp in seconds. ### Method Rust Function Signature ### Response - **u64** - The current Unix timestamp. ``` -------------------------------- ### Algorithm Selection, Encoding, and Decoding with jsonwebtoken Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/algorithms.md Demonstrates selecting an algorithm (RS256), encoding claims into a JWT, and then decoding it with validation. Ensure you use actual RSA keys in production environments. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{ encode, decode, Header, EncodingKey, DecodingKey, Validation, Algorithm, AlgorithmFamily, }; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, exp: u64, } // Choose algorithm let algorithm = Algorithm::RS256; let family = algorithm.family(); println!("Selected: {:?}", algorithm); println!("Family: {:?}", family); println!("All RSA algorithms: {:?}", AlgorithmFamily::Rsa.algorithms()); // Encode let header = Header::new(algorithm); let claims = Claims { sub: "user".to_string(), exp: 9999999999, }; // In real usage, load actual RSA keys let encoding_key = EncodingKey::from_secret(b"secret"); let token = encode(&header, &claims, &encoding_key).unwrap(); // Decode with validation let mut validation = Validation::new(algorithm); // Or allow any algorithm in the family: // let mut validation = Validation::new_for_family(family); let decoding_key = DecodingKey::from_secret(b"secret"); match decode::(&token, &decoding_key, &validation) { Ok(data) => println!("Valid token: {:?}", data.claims), Err(e) => eprintln!("Invalid: {}", e), } ``` -------------------------------- ### Get Current Timestamp Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Retrieves the current Unix timestamp as a u64. Useful for setting expiration or issued-at claims. ```rust pub fn get_current_timestamp() -> u64 ``` -------------------------------- ### Loading PEM RSA Encoding Key Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to load an RSA private key from PEM-encoded bytes for token encoding using the 'use_pem' feature. ```rust // PEM key loading is available use jsonwebtoken::EncodingKey; let key = EncodingKey::from_rsa_pem(pem_bytes)?; ``` -------------------------------- ### Get Algorithm Family Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/algorithms.md Use the `family()` method to determine the classification of a JWT algorithm (Hmac, Rsa, Ec, or Ed). ```rust use jsonwebtoken::Algorithm; assert_eq!(Algorithm::HS256.family(), jsonwebtoken::AlgorithmFamily::Hmac); assert_eq!(Algorithm::RS256.family(), jsonwebtoken::AlgorithmFamily::Rsa); assert_eq!(Algorithm::ES256.family(), jsonwebtoken::AlgorithmFamily::Ec); assert_eq!(Algorithm::EdDSA.family(), jsonwebtoken::AlgorithmFamily::Ed); ``` -------------------------------- ### Loading PEM RSA Decoding Key Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to load an RSA public key from PEM-encoded bytes for token decoding using the 'use_pem' feature. ```rust use jsonwebtoken::DecodingKey; let key = DecodingKey::from_rsa_pem(pem_bytes?); ``` -------------------------------- ### Configure Crypto Feature Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/crypto.md Choose exactly one crypto feature for your project. If no feature is enabled, ensure CryptoProvider::install_default() is called before JWT operations. ```toml [dependencies] # Option 1: AWS LC jsonwebtoken = { version = "10", features = ["aws_lc_rs"] } # Option 2: Rust Crypto jsonwebtoken = { version = "10", features = ["rust_crypto"] } # Option 3: Custom provider (neither feature) jsonwebtoken = { version = "10", default-features = false, features = ["use_pem"] } ``` -------------------------------- ### Get Kind of DecodingKey Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/decoding.md Inspect the specific type of the DecodingKey, which can be a raw secret/DER or RSA modulus/exponent pair. This helps in understanding how the key is stored. ```rust use jsonwebtoken::DecodingKey; let key = DecodingKey::from_secret(b"secret"); match key.kind() { jsonwebtoken::DecodingKeyKind::SecretOrDer(_) => println!("Secret"), jsonwebtoken::DecodingKeyKind::RsaModulusExponent { .. } => println!("RSA"), } ``` -------------------------------- ### Use RustCrypto Backend Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md Configure jsonwebtoken to use pure Rust implementations from the RustCrypto project. This is suitable for WASM targets and has no external C dependencies. ```toml [dependencies] jsonwebtoken = { version = "10", features = ["rust_crypto"] } ``` -------------------------------- ### Working with JWK in Rust Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/jwk.md Demonstrates creating a JWK from an HMAC secret and parsing a JWK from a JSON string. Requires `jsonwebtoken`, `serde_json`, and `Algorithm` imports. ```rust use jsonwebtoken::{EncodingKey, DecodingKey, Algorithm}; use jsonwebtoken::jwk::Jwk; // From an HMAC secret let secret_key = EncodingKey::from_secret(b"my-secret"); let jwk = Jwk::from_encoding_key(&secret_key, Algorithm::HS256).unwrap(); let json = serde_json::to_string_pretty(&jwk).unwrap(); println!("HMAC JWK:\n{}", json); // Parse JWK from JSON let jwk_json = r#"{ "kty": "RSA", "alg": "RS256", "kid": "my-key-id", "use": "sig", "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw", "e": "AQAB" }"#; let jwk: Jwk = serde_json::from_str(jwk_json).unwrap(); println!("JWK is supported: {}", jwk.is_supported()); let decoding_key = DecodingKey::from_jwk(&jwk).unwrap(); // Use decoding_key to verify tokens... ``` -------------------------------- ### Get Algorithm Family of DecodingKey Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/decoding.md Retrieve the algorithm family (Hmac, Rsa, Ec, or Ed) associated with a DecodingKey. This is useful for verifying key compatibility. ```rust use jsonwebtoken::DecodingKey; let key = DecodingKey::from_secret(b"my-secret"); assert_eq!(key.family(), jsonwebtoken::AlgorithmFamily::Hmac); ``` -------------------------------- ### Build JWT Header with Custom Fields Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/header.md Demonstrates how to create a JWT header, set a key ID (kid), and add custom fields to the header's extras. This is useful for including non-standard metadata in your tokens. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{encode, Header, EncodingKey, Extras, Algorithm}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, exp: u64, } let mut header = Header::new(Algorithm::HS512); header.kid = Some("my-key-id".to_string()); // Add custom headers header.extras.insert("custom_claim", "custom_value"); header.extras.insert("version", 1); let claims = Claims { sub: "user@example.com".to_string(), exp: 1234567890, }; let key = EncodingKey::from_secret(b"secret"); let token = encode(&header, &claims, &key).unwrap(); // Token header will include typ, alg, kid, custom_claim, version ``` -------------------------------- ### Get Custom Header Field Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/header.md Retrieves and deserializes a custom header value using its key. Returns None if the key does not exist. Errors if deserialization fails. ```rust use jsonwebtoken::{Header, Extras, Algorithm}; let mut header = Header::new(Algorithm::HS256); header.extras.insert("custom_field", "custom_value"); let value: Option = header.extras.get("custom_field").unwrap(); assert_eq!(value, Some("custom_value".to_string())); ``` -------------------------------- ### Get Algorithm Family of EncodingKey Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/encoding.md Retrieves the algorithm family (Hmac, Rsa, Ec, or Ed) associated with an EncodingKey. This is useful for verifying the key type before use. ```rust use jsonwebtoken::EncodingKey; let key = EncodingKey::from_secret(b"my-secret"); assert_eq!(key.family(), jsonwebtoken::AlgorithmFamily::Hmac); ``` -------------------------------- ### Configure Internal Microservice Token Validation (RSA) Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md Set up validation for internal microservice tokens using RSA algorithms. Enables checking the 'not before' (nbf) claim for activation time. ```rust use jsonwebtoken::{Validation, AlgorithmFamily}; let mut validation = Validation::new_for_family(AlgorithmFamily::Rsa); validation.leeway = 5; // Minimal skew for trusted network validation.set_issuer(&["auth-service"]); validation.validate_nbf = true; // Check activation time ``` -------------------------------- ### RSA Keys from PEM Files for JWT Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Shows how to load RSA private and public keys from PEM files for encoding and decoding JWTs using RS256. Ensure the file paths are correct. ```rust use std::fs; use jsonwebtoken::{encode, decode, Header, EncodingKey, DecodingKey, Validation, Algorithm}; // Load keys from PEM files let private_key = fs::read("private.pem")?; let public_key = fs::read("public.pem")?; let enc_key = EncodingKey::from_rsa_pem(&private_key)?; let dec_key = DecodingKey::from_rsa_pem(&public_key)?; // Use for encoding/decoding let header = Header::new(Algorithm::RS256); let token = encode(&header, &claims, &enc_key)?; let token_data = decode::(&token, &dec_key, &Validation::new(Algorithm::RS256))?; ``` -------------------------------- ### Encode JWT Claims in Rust Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Example of encoding custom claims into a JSON Web Token (JWT) using the jsonwebtoken crate. Requires serde for serialization and deserialization. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{encode, Header, EncodingKey, Algorithm}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, company: String, exp: u64, // Expiration time as UTC timestamp } fn main() -> Result<(), Box> { let my_claims = Claims { sub: "user@example.com".to_owned(), company: "ACME".to_owned(), exp: 10000000000, }; let key = EncodingKey::from_secret(b"secret"); let token = encode(&Header::default(), &my_claims, &key)?; println!("Token: {}", token); Ok(()) } ``` -------------------------------- ### KeyUtils Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/crypto.md Utility functions for JWK processing and key component extraction. ```APIDOC ## KeyUtils Utility functions for JWK processing and key component extraction. ### Fields - `rsa_pub_components_from_private_key`: Extracts RSA public components (n, e) from a DER private key. - `rsa_pub_components_from_public_key`: Extracts RSA public components (n, e) from a DER public key. - `ec_pub_components_from_private_key`: Extracts EC public components (curve, x, y) from a DER private key and an Algorithm. - `ed_pub_components_from_private_key`: Extracts EdDSA public key bytes from a DER private key and an EllipticCurve. **Note:** These functions are used internally for converting keys to JWK format. ``` -------------------------------- ### Safely Using insecure_decode in Rust Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/dangerous-functions.md Demonstrates the correct way to use `insecure_decode` from the `jsonwebtoken::dangerous` module. It includes explicit import, clear documentation of why the operation is safe within the specific context (token origin, encryption, and purpose), and minimal scope for claim extraction. ```rust use jsonwebtoken::dangerous::insecure_decode; fn extract_subject_from_database_token(token: &str) -> Result { // SAFETY: This token came from our own PostgreSQL database, // encrypted at rest. It was validated and stored by our auth service. // We're only extracting the 'sub' claim for an audit log. // If the token is modified or tampered with, the worst case is // an incorrect audit log entry (low severity). #[derive(serde::Deserialize)] struct Claims { sub: String, } let token_data = insecure_decode::(token)?; Ok(token_data.claims.sub) } ``` -------------------------------- ### CryptoProvider::install_default Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/crypto.md Sets this `CryptoProvider` as the default for the process. This function can be called at most once per process execution and must be called before any JWT operations if not using an auto-selected provider from features. ```APIDOC ## CryptoProvider::install_default ### Description Sets this `CryptoProvider` as the default for the process. ### Method `install_default` ### Signature ```rust pub fn install_default(&'static self) -> std::result::Result<(), &'static Self> ``` ### Returns `Ok(())` on success, or `Err(&'static Self)` if a default is already installed. ### Note Can be called at most once per process execution. Must be called before any JWT operations if not using auto-selected provider from features. ### Example ```rust // Only needed if you have a custom provider or no default feature enabled use jsonwebtoken::crypto::CryptoProvider; let provider = my_custom_provider(); provider.install_default() .expect("CryptoProvider should only be installed once"); ``` ``` -------------------------------- ### Enable Default Feature: use_pem Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md The `use_pem` feature is enabled by default and allows loading keys from PEM format files. To disable it, explicitly set `default-features = false` and specify other features. ```toml [dependencies] jsonwebtoken = "10" # use_pem is enabled by default ``` ```toml [dependencies] jsonwebtoken = { version = "10", default-features = false, features = ["aws_lc_rs"] } ``` -------------------------------- ### Example Usage of Result Type Alias in encode Function Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how the `Result` type alias is used in function signatures, specifically in the `encode` function. This provides a consistent error handling pattern. ```rust pub fn encode( header: &Header, claims: &T, key: &EncodingKey, ) -> Result // equivalent to std::result::Result ``` -------------------------------- ### Import necessary structs for jsonwebtoken Source: https://github.com/keats/jsonwebtoken/blob/master/README.md Import the required structs and functions from the `serde` and `jsonwebtoken` crates for JWT operations. ```rust use serde::{Serialize, Deserialize}; use jsonwebtoken::{encode, decode, Header, Extras, Algorithm, Validation, EncodingKey, DecodingKey}; ``` -------------------------------- ### Loading PEM EC Encoding Key Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to load an Elliptic Curve (EC) private key from PEM-encoded bytes for token encoding using the 'use_pem' feature. ```rust use jsonwebtoken::EncodingKey; let key = EncodingKey::from_ec_pem(pem_bytes?); ``` -------------------------------- ### Create JWK from Decoding Key Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/jwk.md Create a JWK from a decoding (public) key. An optional algorithm can be provided to be included in the JWK. ```rust use jsonwebtoken::{DecodingKey, Algorithm}; use jsonwebtoken::jwk::Jwk; let key = DecodingKey::from_secret(b"secret"); let jwk = Jwk::from_decoding_key(&key, Some(Algorithm::HS256)).unwrap(); ``` -------------------------------- ### Reference Documentation Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/INDEX.md Documentation for types, errors, configuration, unsafe operations, and the project overview. ```APIDOC ## Complete Type Reference ### Description Lists all public types with their import paths, properties, constraints, generic parameters, feature-gated types, safe/zeroizing types, and a type-to-module mapping. ### Module [types.md](types.md) ``` ```APIDOC ## Error Handling ### Description Documents the `Error` and `ErrorKind` types, all 22 error variants with trigger conditions, error handling patterns, type conversions, and common error scenarios. ### Module [errors.md](errors.md) ``` ```APIDOC ## Build and Runtime Configuration ### Description Covers Cargo features (use_pem, aws_lc_rs, rust_crypto), feature selection rules, runtime `Validation` configuration, time-based claim settings, audience, issuer, subject configuration, and common configuration scenarios. ### Module [configuration.md](configuration.md) ``` ```APIDOC ## Unsafe Operations ### Description Details the `insecure_decode()` function and its risks, guidance on when to use unsafe functions, security checklists, safe alternatives, and comparison with secure decoding. ### Module [dangerous-functions.md](dangerous-functions.md) ``` ```APIDOC ## Overview and Quick Start ### Description Provides project information, supported algorithms, installation guide, basic encoding/decoding examples, module structure, common workflows, and security considerations. ### Module [README.md](README.md) ``` -------------------------------- ### from_rsa_raw_components Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/decoding.md Creates a `DecodingKey` from RSA public key components already decoded as byte slices. ```APIDOC ## `from_rsa_raw_components(modulus: &[u8], exponent: &[u8])` ### Description Creates a `DecodingKey` from RSA public key components already decoded as byte slices. ### Method `from_rsa_raw_components` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **modulus** (`&[u8]`) - Required - Raw RSA modulus bytes - **exponent** (`&[u8]`) - Required - Raw RSA exponent bytes ### Request Example ```rust use jsonwebtoken::DecodingKey; let modulus = vec![/* ... */]; let exponent = vec![/* ... */]; let key = DecodingKey::from_rsa_raw_components(&modulus, &exponent); ``` ### Response #### Success Response (200) - **DecodingKey** - The RSA key. #### Response Example ```rust // Example response structure (actual type is DecodingKey) // let key = ...; ``` ``` -------------------------------- ### Loading PEM EC Decoding Key Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to load an Elliptic Curve (EC) public key from PEM-encoded bytes for token decoding using the 'use_pem' feature. ```rust use jsonwebtoken::DecodingKey; let key = DecodingKey::from_ec_pem(pem_bytes?); ``` -------------------------------- ### Create RSA DecodingKey from Raw Components Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/decoding.md Use this method to create an RSA `DecodingKey` when you have the raw modulus and exponent bytes. ```rust use jsonwebtoken::DecodingKey; let modulus = vec![/* ... */]; let exponent = vec![/* ... */]; let key = DecodingKey::from_rsa_raw_components(&modulus, &exponent); ``` -------------------------------- ### Add Multiple Algorithms to Validation Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md Initialize a `Validation` instance and then add additional algorithms to its list of permitted algorithms. ```rust let mut validation = Validation::new(Algorithm::RS256); validation.algorithms.push(Algorithm::RS384); ``` -------------------------------- ### Default Header Creation Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/header.md Creates a header with HS256 algorithm and default values. ```APIDOC ## Default for Header Creates a header with HS256 algorithm and default values. **Example:** ```rust use jsonwebtoken::Header; let header = Header::default(); assert_eq!(header.alg, jsonwebtoken::Algorithm::HS256); ``` ``` -------------------------------- ### Add jsonwebtoken to Cargo.toml Source: https://github.com/keats/jsonwebtoken/blob/master/README.md Add the jsonwebtoken crate to your Cargo.toml file. You must select either `aws_lc_rs` or `rust_crypto` as a backend, or provide your own `CryptoProvider`. ```toml jsonwebtoken = { version = "11", features = ["aws_lc_rs"] } # If you do not need pem decoding, you can disable the default feature `use_pem` that way: # jsonwebtoken = {version = "11", default-features = false, features = ["aws_lc_rs"] } serde = {version = "1.0", features = ["derive"] } ``` -------------------------------- ### Feature Selection Rules for Crypto Backends Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md Ensure exactly one cryptographic backend feature (`aws_lc_rs` or `rust_crypto`) is enabled. Enabling both or neither (without a custom provider) is incorrect. ```toml # ✓ CORRECT: aws_lc_rs jsonwebtoken = { version = "10", features = ["aws_lc_rs"] } ``` ```toml # ✓ CORRECT: rust_crypto jsonwebtoken = { version = "10", features = ["rust_crypto"] } ``` ```toml # ✗ WRONG: Both enabled jsonwebtoken = { version = "10", features = ["aws_lc_rs", "rust_crypto"] } ``` ```toml # ✗ WRONG: Neither enabled (unless providing custom provider) jsonwebtoken = { version = "10", default-features = false } ``` -------------------------------- ### Generate RSA PKCS1 Keys and Certificate Source: https://github.com/keats/jsonwebtoken/blob/master/tests/rsa/README.md Use these OpenSSL commands to generate RSA private and public keys in PKCS1 format, along with a certificate signing request and a self-signed certificate. ```bash openssl genrsa -out private_rsa_pkcs1.pem ``` ```bash openssl rsa -in private_rsa_pkcs1.pem -RSAPublicKey_out -out public_rsa_pkcs1.pem ``` ```bash openssl req -new -key private_rsa_pkcs1.pem -out certificate_rsa_pkcs1.csr ``` ```bash openssl x509 -req -sha256 -days 358000 -in certificate_rsa_pkcs1.csr -signkey private_rsa_pkcs1.pem -out certificate_rsa_pkcs1.crt ``` -------------------------------- ### KeyAlgorithm Enum Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/jwk.md Enumerates supported algorithms associated with a JWK. ```rust #[non_exhaustive] pub enum KeyAlgorithm { HS256, HS384, HS512, ES256, ES384, RS256, RS384, RS512, PS256, PS384, PS512, EdDSA, RSA1_5, RSA_OAEP, RSA_OAEP_256, UNKNOWN_ALGORITHM, } ``` -------------------------------- ### Create Validation with Single Algorithm Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md Initialize a new `Validation` instance with a specific algorithm, such as RS256. ```rust let validation = Validation::new(Algorithm::RS256); ``` -------------------------------- ### Create ECDSA EncodingKey from PEM Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/encoding.md Use this method to create an `EncodingKey` from an ECDSA private key in PEM format. This requires the `use_pem` feature to be enabled. The key must be PKCS#8-encoded. ```rust #[cfg(feature = "use_pem")] pub fn from_ec_pem(key: &[u8]) -> Result ``` ```rust use jsonwebtoken::EncodingKey; let pem = b"-----BEGIN PRIVATE KEY-----\n..."; let key = EncodingKey::from_ec_pem(pem).unwrap(); ``` -------------------------------- ### Configure Leeway (Clock Skew Tolerance) Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md Set the leeway in seconds to allow for clock skew between systems. This tolerance is applied to 'exp' and 'nbf' claims. Default is 60 seconds. ```rust validation.leeway = 60; // Default: 60 seconds ``` -------------------------------- ### JWK from Public URL for JWT Decoding Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Illustrates how to decode a JWT using a JSON Web Key (JWK) fetched from a public URL. The JWK must be correctly formatted JSON. ```rust use jsonwebtoken::{DecodingKey, decode, Validation, Algorithm}; // Parse JWK from JSON let jwk_json = r#"{{ "kty": "RSA", "n": "...", "e": "AQAB" }}"#; let jwk: jsonwebtoken::jwk::Jwk = serde_json::from_str(jwk_json)?; let key = DecodingKey::from_jwk(&jwk)?; let token_data = decode::(token, &key, &Validation::new(Algorithm::RS256))?; ``` -------------------------------- ### as_bytes Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/encoding.md Returns the raw bytes of the key. Intended for use when defining custom CryptoProvider implementations. ```APIDOC ## `as_bytes()` ### Description Returns the raw bytes of the key. Intended for use when defining custom `CryptoProvider` implementations. ### Method Signature `as_bytes(&self) -> &[u8]` ### Parameters This method takes no parameters. ### Returns `&[u8]` — Reference to the underlying key bytes. ``` -------------------------------- ### Loading PEM Ed Encoding Key Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to load an Edwards curve (Ed) private key from PEM-encoded bytes for token encoding using the 'use_pem' feature. ```rust use jsonwebtoken::EncodingKey; let key = EncodingKey::from_ed_pem(pem_bytes?); ``` -------------------------------- ### Import Common Items from Root Module Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Re-exports the most commonly used items from the main jsonwebtoken crate for convenience. ```rust use jsonwebtoken::{ // Main functions encode, decode, decode_header, get_current_timestamp, // Main types Algorithm, AlgorithmFamily, EncodingKey, DecodingKey, Header, Extras, Validation, TokenData, }; ``` -------------------------------- ### Simple HMAC Token Encoding and Decoding Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/README.md Demonstrates how to encode and decode a JWT using a shared secret key with the HS256 algorithm. Ensure the secret key and validation algorithm match. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{encode, decode, Header, EncodingKey, DecodingKey, Validation, Algorithm}; #[derive(Debug, Serialize, Deserialize)] struct Claims { user_id: String, } let secret = b"my-secret-key"; let claims = Claims { user_id: "123".to_string() }; // Encode let token = encode( &Header::default(), &claims, &EncodingKey::from_secret(secret), )?; // Decode let token_data = decode::( &token, &DecodingKey::from_secret(secret), &Validation::new(Algorithm::HS256), )?; println!("User ID: {}", token_data.claims.user_id); ``` -------------------------------- ### DecodingKey::from_rsa_components(modulus: &str, exponent: &str) Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/decoding.md Creates a DecodingKey from RSA public key components (modulus and exponent) as base64-encoded strings, useful for JWK format. ```APIDOC ## DecodingKey::from_rsa_components(modulus: &str, exponent: &str) ### Description Creates a `DecodingKey` from RSA public key components as base64-encoded strings (n, e). This is useful when loading keys from JWK format. ### Method `pub fn from_rsa_components(modulus: &str, exponent: &str) -> Result` ### Parameters #### Path Parameters - **modulus** (`&str`) - Required - Base64-encoded RSA modulus (n) - **exponent** (`&str`) - Required - Base64-encoded RSA exponent (e) ### Returns `Result` — The RSA key or an error. ### Throws - `ErrorKind::Base64` - If base64 decoding fails - `ErrorKind::InvalidRsaKey` - If components are invalid ### Example ```rust use jsonwebtoken::DecodingKey; let key = DecodingKey::from_rsa_components( "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw", "AQAB", ).unwrap(); ``` ``` -------------------------------- ### jsonwebtoken Crate Import Paths Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Imports all primary types, functions, and modules from the jsonwebtoken crate root. This is the standard way to access the crate's functionality. ```rust use jsonwebtoken::{ // Main types Algorithm, AlgorithmFamily, EncodingKey, DecodingKey, DecodingKeyKind, Header, Extras, Validation, TokenData, // Functions encode, decode, decode_header, get_current_timestamp, // JWK module jwk::{Jwk, PublicKeyUse, KeyOperations, KeyAlgorithm}, // JWS module jws::Jws, // Crypto module crypto::{CryptoProvider, JwtSigner, JwtVerifier}, // Error types errors::{Error, ErrorKind, Result}, }; ``` -------------------------------- ### Use AWS Libcrypto Backend Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md Configure jsonwebtoken to use AWS Libcrypto for cryptographic operations, recommended for production. This backend supports RSA, ECDSA, and EdDSA algorithms and can be FIPS-capable. ```toml [dependencies] jsonwebtoken = { version = "10", features = ["aws_lc_rs"] } ``` -------------------------------- ### Create DecodingKey from RSA PEM Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/decoding.md Load an RSA public key for verification from PEM-encoded bytes. This function requires the `use_pem` feature to be enabled and returns a Result, failing on invalid RSA keys. ```rust use jsonwebtoken::DecodingKey; let pem = b"-----BEGIN PUBLIC KEY-----\n..."; let key = DecodingKey::from_rsa_pem(pem).unwrap(); ``` -------------------------------- ### WASM Support Dependencies Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/configuration.md Configure dependencies for WebAssembly targets, including js-sys and getrandom. Additional dev-dependencies like wasm-bindgen-test are included for specific WASM environments. ```toml [target.'cfg(target_arch = "wasm32")'.dependencies] js-sys = "0.3" getrandom = "0.2" ``` ```toml [target.'cfg(all(target_arch = "wasm32", not(any(target_os = "emscripten", target_os = "wasi"))))'.dev-dependencies] wasm-bindgen-test = "0.3.1" time = { version = "0.3", features = ["wasm-bindgen"] } ``` -------------------------------- ### Algorithm::from_str() Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/api-reference/algorithms.md Parses an algorithm from a string representation. ```APIDOC ### FromStr Trait Parses an algorithm from a string. ```rust impl FromStr for Algorithm { type Err = Error; fn from_str(s: &str) -> Result } ``` **Supported Strings:** - "HS256", "HS384", "HS512" - "ES256", "ES384" - "RS256", "RS384", "RS512" - "PS256", "PS384", "PS512" - "EdDSA" **Example:** ```rust use std::str::FromStr; use jsonwebtoken::Algorithm; let alg = Algorithm::from_str("RS256").unwrap(); assert_eq!(alg, Algorithm::RS256); let result = Algorithm::from_str("UNKNOWN"); assert!(result.is_err()); ``` ``` -------------------------------- ### Loading PEM Ed Decoding Key Source: https://github.com/keats/jsonwebtoken/blob/master/_autodocs/types.md Demonstrates how to load an Edwards curve (Ed) public key from PEM-encoded bytes for token decoding using the 'use_pem' feature. ```rust use jsonwebtoken::DecodingKey; let key = DecodingKey::from_ed_pem(pem_bytes?); ```