Module std::crypto::jwt

JSON Web Token encoding and validation.

Encode, decode, and validate JWTs using HMAC or RSA algorithms.

Examples

import std::crypto::jwt;

fn main() {
    let token = jwt.encode("{\"sub\":\"1234\"}", "secret", "HS256");
    if jwt.validate(token, "secret", "HS256") {
        let payload = jwt.decode(token, "secret", "HS256");
        println(payload);
    }
}

Contents

Functions

Function algo_to_i32

fn algo_to_i32(algorithm: String) -> i32

Map an algorithm name (e.g. "HS256") to its integer code for the FFI layer.

Function encode

pub fn encode(payload: String, secret: String, algorithm: String) -> String

Encode a JSON payload into a signed JWT string.

Examples

let token = jwt.encode("{\"sub\":\"user1\"}", "my_secret", "HS256");

Function decode

pub fn decode(token: String, secret: String, algorithm: String) -> String

Decode and verify a JWT, returning its payload as a JSON string.

Panics if the token signature is invalid.

Examples

let payload = jwt.decode(token, "my_secret", "HS256");

Function decode_insecure

pub fn decode_insecure(token: String) -> String

Decode a JWT without verifying its signature.

Warning: This does not validate the token. Only use for inspecting untrusted tokens when you don't need authenticity.

Examples

let payload = jwt.decode_insecure(token);

Function validate

pub fn validate(token: String, secret: String, algorithm: String) -> bool

Validate a JWT signature and expiration.

Returns true if the token is valid, false otherwise.

Examples

if jwt.validate(token, "my_secret", "HS256") {
    println("valid");
}