jwtea 0.1.0

Lean JWT library
Documentation
//! Decode a JWT and inspect its payload.

use jwtea::{BasicValidator, Jwk, VerifyingKey};


/// You have create your own type with claims you are about. This ensures we
/// do not deserialize claims that are never used.
#[derive(Debug, serde::Deserialize)]
struct MyClaims {
    name: String,
    roles: Vec<String>,
}

#[pollster::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Prepare cryptographic key. See `tests/data/ed25519.rs` for private key.
    let jwk: Jwk<'static> = serde_json::from_value(serde_json::json!({
        "alg": "EdDSA",
        "crv": "Ed25519",
        "kty": "OKP",
        "use": "sig",
        "x": "E8MyvDalXtfz6xE7-Sjq1-rDOmpl-QpEsVY3OU_hH_U"
    }))?;
    let key = VerifyingKey::from_jwk(&jwk)?;

    // Decode JWT
    let jwt = "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.\
        eyJleHAiOjQwMTIzNDU2NzgsIm5hbWUiOiJNb3JnYW4gWXUiLCJyb2xlcyI6WyJST0xFX0JBTkFOQSJdfQ.\
        mDI2Hoo8AKiEWoTG9hhdbR3vrG3kRLMMgkmj1KBmxi3uAGp6Fa4dK6TSbKb0BktjCAA77KpydRS1THGYW1qrCg";
    let (is_admin, name) = jwtea::decode::<(), MyClaims, _>(
        jwt,
        &key,
        &BasicValidator::default(),
        |_header, payload| {
            // In this callback, you typically you inspect the payload and extract
            // and return all information you are interested in.
            let is_admin = payload.extra_fields.roles.iter().any(|role| role == "ROLE_ADMIN");
            (is_admin, payload.extra_fields.name)
        },
    ).await?;

    println!("{name} is {}", if is_admin { "admin" } else { "NOT admin" });

    Ok(())
}