Sample code for 30+ languages & platforms
Zig

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 Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // 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.

    const jwt = try chilkat.Jwt.init();
    defer jwt.deinit();

    // Build the JOSE header
    const jose = try chilkat.JsonObject.init();
    defer jose.deinit();
    // Use HS256.  Pass the string "HS384" or "HS512" to use a different algorithm.
    try jose.appendString("alg", "HS256");
    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");

    // 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);

    // Set the "not process before" timestamp to now.
    try claims.addIntAt(-1, "nbf", cur_date_time);

    // 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);

    const str_jwt = try jwt.createJwt(alloc, try jose.emit(alloc), try claims.emit(alloc), "secret");

    std.debug.print("{s}\n", .{str_jwt});
}