Rust
Rust
Create JWT Using HS256, HS384, or HS512
See more JSON Web Token (JWT) Examples
Demonstrates how to create a JWT using HS256, HS384, or HS512. (HS256 is JWT's acronym for HMAC-SHA256.) When HMAC is used, the secret is a shared secret (i.e. password) that both client and server know beforehand.This example also demonstrates how to include time constraints:
- nbf: Not Before Time
- exp: Expiration Time
- iat: Issue At Time
Chilkat Rust Downloads
// Demonstrates how to create an HMAC JWT using a shared secret (password).
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let jwt = chilkat::Jwt::new();
// Build the JOSE header
let jose = chilkat::JsonObject::new();
// Use HS256. Pass the string "HS384" or "HS512" to use a different algorithm.
let _ = jose.append_string("alg", "HS256").is_ok();
let _ = jose.append_string("typ", "JWT").is_ok();
// Now build the JWT claims (also known as the payload)
let claims = chilkat::JsonObject::new();
let _ = claims.append_string("iss", "http://example.org").is_ok();
let _ = claims.append_string("sub", "John").is_ok();
let _ = claims.append_string("aud", "http://example.com").is_ok();
// Set the timestamp of when the JWT was created to now.
let cur_date_time = jwt.gen_numeric_date(0);
let _ = claims.add_int_at(-1, "iat", cur_date_time).is_ok();
// Set the "not process before" timestamp to now.
let _ = claims.add_int_at(-1, "nbf", cur_date_time).is_ok();
// Set the timestamp defining an expiration time (end time) for the token
// to be now + 1 hour (3600 seconds)
let _ = claims.add_int_at(-1, "exp", cur_date_time + 3600).is_ok();
// Produce the smallest possible JWT:
jwt.set_auto_compact(true);
let str_jwt = jwt.create_jwt(&jose.emit().unwrap_or_default(), &claims.emit().unwrap_or_default(), "secret").unwrap_or_default();
println!("{}", str_jwt);