Rust JWT Library
A simple Rust library for encoding, decoding, and validating JSON Web Tokens (JWTs) implemented using Rust Crypto libraries. This library supports HMAC, RSA, and ECDSA and it can be compiled as Rust library or WebAssembly.
Getting Started
Add this library to your Cargo.toml
dependencies:
[]
= "0.1.0"
Example: Encoding and Decoding a JWT
use json;
use ;
Example: Decoding Only (No Signature Verification)
use ;
Supported Algorithms
The library supports the following signing and verifying algorithms:
- HMAC:
HS256
,HS384
,HS512
- RSA:
RS256
,RS384
,RS512
,PS256
,PS384
,PS512
- ECDSA:
ES256
,ES256K
,ES384
,ES512
Installation and Setup
To use this library, simply add it to your project's dependencies as shown in the Getting Started section.
WebAssembly Support
To compile this library to WebAssembly, first install the target:
Then, build the library for the WebAssembly target:
Building
To build the Rust library:
Testing
To run the test suite:
Documentation
Encoding a JWT
To create a signed JWT, you need a header, payload, and a signing key. Use the encode
function to generate a signed JWT:
use ;
use json;
let header = new;
let payload = json!;
let signing_key = from_secret;
let token = encode.expect;
Decoding a JWT
To decode and validate a JWT, use the decode
function along with the verification key and validation options:
use ;
let verification_key = from_secret;
let validation_options = default.with_algorithm;
let decoded = decode.expect;
println!;
println!;
Encoding a JWT with RSA Key
To create a signed JWT using an RSA key, you need to load the private key and use it for signing:
use ;
use json;
use fs;
let rsa_private_key = read_to_string
.expect;
let header = new;
let payload = json!;
let signing_key = from_rsa_pem
.expect;
let token = encode
.expect;
println!;
Decoding a JWT with RSA Key
To decode and verify a JWT using an RSA public key, use the decode function along with the verification key and validation options:
use ;
use fs;
let rsa_public_key = read_to_string
.expect;
let verification_key = from_rsa_pem
.expect;
let validation_options = default.with_algorithm;
let decoded = decode
.expect;
println!;
println!;
Error Handling
Errors in this library are represented by the Error
enum, which provides detailed messages for various failure cases, such as invalid signatures, expired tokens, and unsupported algorithms.
Contributing
Contributions are welcome! Please see the CONTRIBUTING.md file for guidelines.
License
This project is licensed under the MIT License. See the LICENSE file for details.