parse jwt tokens in rust

To parse or decode a JWT token in Rust, we can use the jsonwebtoken crate. Here's an example of how to parse a JWT token and extract its payload data:

main.rs
use jsonwebtoken::{decode, DecodingKey, Validation};

fn parse_jwt_token(token: &str, secret: &str) -> Result<(), String> {
    // Define the decoding key and validation parameters
    let decoding_key = DecodingKey::from_secret(secret.as_ref());
    let validation = Validation::default();

    // Decode the token and extract its payload data
    match decode::<HashMap<String, String>>(&token, &decoding_key, &validation) {
        Ok(payload) => {
            // Token is valid, extract data from payload
            let user_id = payload["sub"].parse::<i32>().unwrap();
            let user_role = payload["role"].to_string();
            println!("User {} has role {}", user_id, user_role);
            Ok(())
        },
        Err(err) => {
            // Token is invalid
            Err(format!("Failed to decode JWT token: {}", err))
        }
    }
}

fn main() {
    let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
    let secret = "secret_key";
    parse_jwt_token(token, secret).unwrap();
}
1129 chars
29 lines

In this example, we first define the decoding key and validation parameters. We then call the decode function from the jsonwebtoken crate with the provided JWT token, decoding key, and validation parameters. If the token is valid, we extract its payload data and print it to the console.

Note that the decode function requires us to specify the type of the payload data. In this example, we use a HashMap<String, String> to represent the payload, but you can change this to match the format of your own JWT tokens.

related categories

gistlibby LogSnag