Module std::crypto::jwt

JSON Web Token encoding and validation.

Encode, decode, and validate JWTs using HMAC algorithms.

Examples

import std::crypto::jwt;

fn main() {
    match jwt.try_encode("{\"sub\":\"1234\"}", "secret", "HS256") {
        Ok(token) => println(token),
        Err(err) => println(jwt.error_message(err)),
    }
}

Contents

Functions

Function error_message

pub fn error_message(err: JwtError) -> string

Return a human-readable message for a [JwtError].

Function last_error

pub fn last_error() -> JwtError

Return the last JWT error observed on this thread.

Function try_encode

pub fn try_encode(payload: string, secret: string, algorithm: string) -> Result<string, JwtError>

Encode a JSON payload into a signed JWT string.

Returns Err(JwtError) when the payload, key, algorithm, or allocation path fails.

Function encode

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

Encode a JSON payload into a signed JWT string.

Panics on invalid input or verification setup errors. Use try_encode for structured error handling.

Function try_decode

pub fn try_decode(token: string, secret: string, algorithm: string) -> Result<string, JwtError>

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

Returns Err(JwtError) when the token is malformed, expired, signed with a different key, or cannot be allocated.

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 on invalid tokens. Use try_decode for structured error handling.

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");
}

Types

Enum JwtError

Structured JWT errors surfaced by the native C ABI.

Variants

None
AlgorithmUnsupported
InvalidKey
TokenMalformed
SignatureInvalid
ClaimsExpired
AllocationFailure