Skip to main content

Module jwt

Module jwt 

Source
Expand description

Standalone HS256 JWT — sign / verify / decode for magic links, microservice tokens, third-party SSO. See jwt::encode + jwt::decode. Minimal JWT (HS256) — sign, verify, decode.

Standalone alternative to [crate::tenancy::jwt_lifecycle] (which wraps this with refresh + JTI blacklist + sliding rotation, but is gated on the tenancy feature). Reach for this module when you want plain JWTs for:

  • Magic-link tokens that carry a few claims (user id, purpose, exp)
  • Service-to-service tokens (sister to crate::hmac_auth — pick HMAC for AWS-style request signing, JWT for stateless bearer tokens)
  • Single-sign-on tokens you hand to a third party

§Algorithm

HS256 only — symmetric, single shared secret. RS256 / ES256 (public / private keypair) are out of scope: the rustls / ring deps would triple the always-on dep tree, and most callers picking JWT in a single-service codebase use HS256 anyway.

§Quick start

use rustango::jwt::{Claims, encode, decode};
use std::time::Duration;

let secret = b"thirty-two-bytes-of-shared-secret-mat";

let mut claims = Claims::new("user-42")
    .ttl(Duration::from_secs(3600))
    .issuer("api.example.com");
claims.set("role", "admin");

let token = encode(&claims, secret).unwrap();

let verified = decode(&token, secret).unwrap();
assert_eq!(verified.subject(), Some("user-42"));
assert_eq!(verified.get::<String>("role").as_deref(), Some("admin"));

Structs§

Claims
JWT claims — wraps a JSON object so callers can mix standard claims (sub, exp, iat, iss, aud, nbf, jti) with arbitrary extension fields.

Enums§

JwtError

Functions§

decode
Decode + verify an HS256 JWT. Checks signature, exp, and nbf. Does NOT check iss / aud — callers should validate those against expected values from the returned claims.
decode_at
decode but with an explicit “current” time. Useful for tests + for systems with clock skew tolerance baked in elsewhere.
decode_unverified
Decode WITHOUT verifying the signature or temporal claims. Useful for inspecting a token to find which key id signed it (when you rotate keys), then calling decode with the right secret.
encode
Encode + sign claims as an HS256 JWT. Returns the standard three-part base64url-encoded token: header.payload.signature.