Crate jwt_rs

Source
Expand description

A simple Json Web Token crate. The crate let’s you create, sign, verify and extract data from JWT tokens. Data is serialized with serde and serde_json.

§Example

§Verification

Extract the payload from a JWT token if the token is valid.

#[derive(serde::Serialize, serde::Deserialize, PartialEq)]
struct TestPayload {
    is_admin: bool,
    name: String,
    age: u8,
}

const SECRET: &'static str = "This is a very secret secret";

let token_str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc19hZG1pbiI6dHJ1ZSwibmFtZSI6IkpvaG4gRG9lIiwiYWdlIjoxOH0.0mV5XVAmarscyZEwl8PoX4vqVn_JCZSVJRsgnSJTo94";
let token = Token::from_str(token_str)?;
// payload is `Ok(Some(<payload>))`
let payload = token.get_if_valid::<TestPayload>(SECRET);

§Signing

It’s also possible to create and sign a new token:

const SECRET: &'static str = "This is a very secret secret";

#[derive(serde::Serialize, serde::Deserialize)]
struct TestPayload {
    is_admin: bool,
    name: String,
    age: u8,
}
let payload = TestPayload {
    is_admin: true,
    name: String::from("John Doe"),
    age: 18
};
let token = Token::try_new(Algorithm::HS256, payload, SECRET).unwrap();
println!("{}", token);

Structs§

Header
The header part of the JWT token. This part contains the algorithm used to hash the signature.
HeaderDecoded
The actual data that is encoded in the header is stored in this struct. A second struct is used because it’s easyer to decode with serde_json.
Payload
The payload of the JWT token. The payload can contain any JSON formatted data. This is the part where data is stored.
Signature
The signature of the token. This part is used to check that the token is valid and was not tempered with.
Token
A JWT token. Use this struct to sign or verify a token. You can get the payload or verify a token with the Token::from_str function.

Enums§

Algorithm
The hash algorithm that is used to sign the token. Currently, only HMAC (signing with a screet) is supported by this crate.
Error
Errors generated by this crate.