Sample code for 30+ languages & platforms
Zig

S3 List Buckets using an STS Session Token

See more AWS Security Token Service Examples

This is an example showing how to use an STS session token in an Amazon AWS request. This example will list S3 buckets using a previously obtained session token.

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

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // See Get AWS STS Session Token for sample code to get the session token XML.
    const xml_token = try chilkat.Xml.init();
    defer xml_token.deinit();
    xml_token.loadXmlFile("qa_data/tokens/aws_session_token.xml") catch {
        std.debug.print("{s}\n", .{try xml_token.getLastErrorText(alloc)});
        return;
    };

    const rest = try chilkat.Rest.init();
    defer rest.deinit();

    // Connect to the Amazon AWS REST server.
    const b_tls = true;
    const port = 443;
    const b_auto_reconnect = true;
    try rest.connect("s3.amazonaws.com", port, b_tls, b_auto_reconnect);

    // Provide AWS credentials for the REST call.
    const auth_aws = try chilkat.AuthAws.init();
    defer auth_aws.deinit();

    // The purpose of this example is to show how to use the temporary AccessKeyId, SecretAccessKey, and SessionToken.
    auth_aws.setAccessKey(try xml_token.getChildContent(alloc, "GetSessionTokenResult|Credentials|AccessKeyId"));
    auth_aws.setSecretKey(try xml_token.getChildContent(alloc, "GetSessionTokenResult|Credentials|SecretAccessKey"));
    auth_aws.setServiceName("s3");
    try rest.setAuthAws(auth_aws);

    rest.addQueryParam("X-Amz-Security-Token", try xml_token.getChildContent(alloc, "GetSessionTokenResult|Credentials|SessionToken")) catch {};

    const sb_response = try chilkat.StringBuilder.init();
    defer sb_response.deinit();
    rest.fullRequestNoBodySb("GET", "/", sb_response) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    const status_code = rest.getResponseStatusCode();
    std.debug.print("Response status code = {d}\n", .{status_code});

    const xml = try chilkat.Xml.init();
    defer xml.deinit();
    xml.loadSb(sb_response, true) catch {};
    std.debug.print("{s}\n", .{try xml.getXml(alloc)});

    if (status_code != 200) {
        std.debug.print("Failed.  See error information in the XML.\n", .{});
        return;
    }
}