Zig
Zig
bitzlato.com whoami
See more JSON Web Token (JWT) Examples
Demonstrates sending a request to the bitzlato.com whoami endpoint using an ES256 JWT token for authentication.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.
// Use the following ECC key loaded from JWK format.
const jwk = try chilkat.JsonObject.init();
defer jwk.deinit();
try jwk.updateString("kty", "EC");
try jwk.updateString("crv", "P-256");
try jwk.updateString("x", "...");
try jwk.updateString("y", "...");
try jwk.updateString("d", "...");
const ecc_key = try chilkat.PrivateKey.init();
defer ecc_key.deinit();
ecc_key.loadJwk(try jwk.emit(alloc)) catch {
std.debug.print("{s}\n", .{try ecc_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();
try jose.appendString("format", "compact");
try jose.appendString("alg", "ES256");
// Now build the JWT claims (also known as the payload)
// Our JWT claims will contain members as shown here:
// {
// "email":"your_email@example.com",
// "aud":"usr",
// "iat":"1588286154",
// "jti":"555D9123"
// }
const claims = try chilkat.JsonObject.init();
defer claims.deinit();
claims.appendString("jti", "555D9123") catch {};
claims.appendString("email", "your_email@example.com") catch {};
// Set the timestamp of when the JWT was created to now minus 60 seconds
const cur_date_time = jwt.genNumericDate(-60);
try claims.addIntAt(-1, "iat", cur_date_time);
// Set the "not process before" timestamp to now minus 60 seconds
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);
claims.appendString("aud", "usr") catch {};
// Produce the smallest possible JWT:
jwt.setAutoCompact(true);
// Create the JWT token. This is where the RSA signature is created.
const jwt_token = try jwt.createJwtPk(alloc, try jose.emit(alloc), try claims.emit(alloc), ecc_key);
std.debug.print("{s}\n", .{jwt_token});
// Send the HTTPS GET with the jwt_token used for Authorization.
const http = try chilkat.Http.init();
defer http.deinit();
http.setAuthToken(jwt_token);
const response_str = http.quickGetStr(alloc, "https://bitzlato.com/api/auth/whoami") catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
std.debug.print("status code = {d}\n", .{http.getLastStatus()});
std.debug.print("{s}\n", .{response_str});
}