Zig
Zig
Create JWT Using Ed25519 Private Key (EdDSA)
See more JSON Web Token (JWT) Examples
Demonstrates how to create a JWT using an Ed25519 private key. If the private key is Ed25519, which is an EdDSA algorithm, the JOSE header's "alg" member should be set to "EdDSA".Note: This example requires Chilkat v9.5.0.95 or greater.
Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Demonstrates how to create a JWT using an Ed25519 private key.
const priv_key = try chilkat.PrivateKey.init();
defer priv_key.deinit();
// Load an Ed25519 (EdDSA) private key from a PEM file.
priv_key.loadPemFile("qa_data/eddsa/ed25519.pem") catch {
std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
return;
};
const jwt = try chilkat.Jwt.init();
defer jwt.deinit();
// Build the JOSE header
const jose = try chilkat.JsonObject.init();
defer jose.deinit();
// -----------------------------------------------------------------
// Note: This example requires Chilkat v9.5.0.95 or greater.
// -----------------------------------------------------------------
try jose.appendString("alg", "EdDSA");
try jose.appendString("typ", "JWT");
// Now build the JWT claims (also known as the payload)
const claims = try chilkat.JsonObject.init();
defer claims.deinit();
try claims.appendString("iss", "http://example.org");
try claims.appendString("sub", "John");
try claims.appendString("aud", "http://example.com");
// (optional) Set the timestamp of when the JWT was created to now.
const cur_date_time = jwt.genNumericDate(0);
try claims.addIntAt(-1, "iat", cur_date_time);
// (optional) Set the "not process before" timestamp to now.
try claims.addIntAt(-1, "nbf", cur_date_time);
// (optional) Set the timestamp defining an expiration time (end time) for the token
// to be now + 1 hour (3600 seconds)
try claims.addIntAt(-1, "exp", cur_date_time + 3600);
// Produce the smallest possible JWT:
jwt.setAutoCompact(true);
// Create the JWT token.
const token = try jwt.createJwtPk(alloc, try jose.emit(alloc), try claims.emit(alloc), priv_key);
std.debug.print("{s}\n", .{token});
// Example output:
// eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vZXhhbXBsZS5vcmciLCJzdWIiOiJKb2huIiwiYXVkIjoiaHR0cDovL2V4YW1wbGUuY29tIiwiaWF0IjoxNjg3OTcwNjgyLCJuYmYiOjE2ODc5NzA2ODIsImV4cCI6MTY4Nzk3NDI4Mn0.eyfrDJfuWJSJVJPfAUYb_p_c-LF_YULHGRaZx82MLLjMLCCFEEGckp8icuayf5bLW9ah20LzYYt0JgOBIB0RDg
}