Crates.io | jwt_rs |
lib.rs | jwt_rs |
version | 0.1.0 |
source | src |
created_at | 2022-03-15 00:42:27.54681 |
updated_at | 2022-03-15 00:42:27.54681 |
description | A Json Web Token (JWT) implementation for Rust |
homepage | https://github.com/xavierhamel/jwt-rs |
repository | https://github.com/xavierhamel/jwt-rs |
max_upload_size | |
id | 550274 |
size | 18,429 |
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
.
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);
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); // Convert the token to a string.