Sample code for 30+ languages & platforms
Unicode C++ Requires Chilkat v11.6.0+

AWS STS: Download an S3 Object with STS Credentials and Chilkat.Http

See more AWS Security Token Service Examples

Uses the AWS STS Query API version 2011-06-15 and a verified TLS connection to the commercial-partition regional endpoint sts.us-west-2.amazonaws.com. Change the endpoint and signing region together for your deployment. Assumes Chilkat is unlocked.

Keep qa_data/aws/sts.json private and outside web roots/source control. Signed examples require nonempty access_key and secret_key strings; temporary source credentials also require session_token and ISO 8601 expiration. Federation exchanges load their specific fields without AWS keys. The examples do not print credentials, bearer tokens, full responses or diagnostic dumps. Credential-producing examples build a complete in-memory session object with access_key, secret_key, session_token and expiration; integrate that object into your application before it goes out of scope.

Reads private STS XML as in the normalization example, plus qa_data/aws/sts_download.json with bucket and object_key strings. Uses all three temporary credential components with Chilkat.Http.S3_DownloadBd. Supply the raw object key, not a pre-encoded URL. Choose a small object that fits in memory, a general purpose bucket in us-west-2, and a session authorized for s3:GetObject on that object; the earlier bucket-list-only session policy is insufficient. KMS-encrypted objects may also need kms:Decrypt. The request is read-only and writes no file. Redirects are disabled so a region mismatch fails explicitly.

S3 GetObject

AWS references: AssumeRole

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkXmlW.h>
#include <CkDateTimeW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkBinDataW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Load a privately stored STS XML response; never print its contents.
    CkXmlW tokenXml;
    tokenXml.put_Strict(true);
    success = tokenXml.LoadXmlFile(L"qa_data/tokens/aws_session_token.xml");
    if (success != true) {
        wprintf(L"Could not load private STS XML.\n");
        return;
    }

    const wchar_t *credentialPath = L"";
    stringCompare.SetString(tokenXml.tag());
    bool stringMatch1 = stringCompare.ContentsEqual(L"GetSessionTokenResponse",true);
    if (stringMatch1 == true) {
        credentialPath = L"GetSessionTokenResult|Credentials";
    }

    stringCompare.SetString(tokenXml.tag());
    bool stringMatch2 = stringCompare.ContentsEqual(L"AssumeRoleResponse",true);
    if (stringMatch2 == true) {
        credentialPath = L"AssumeRoleResult|Credentials";
    }

    stringCompare.SetString(tokenXml.tag());
    bool stringMatch3 = stringCompare.ContentsEqual(L"AssumeRoleWithWebIdentityResponse",true);
    if (stringMatch3 == true) {
        credentialPath = L"AssumeRoleWithWebIdentityResult|Credentials";
    }

    stringCompare.SetString(tokenXml.tag());
    bool stringMatch4 = stringCompare.ContentsEqual(L"AssumeRoleWithSAMLResponse",true);
    if (stringMatch4 == true) {
        credentialPath = L"AssumeRoleWithSAMLResult|Credentials";
    }

    stringCompare.SetString(tokenXml.tag());
    bool stringMatch5 = stringCompare.ContentsEqual(L"GetFederationTokenResponse",true);
    if (stringMatch5 == true) {
        credentialPath = L"GetFederationTokenResult|Credentials";
    }

    stringCompare.SetString(tokenXml.tag());
    bool stringMatch6 = stringCompare.ContentsEqual(L"GetDelegatedAccessTokenResponse",true);
    if (stringMatch6 == true) {
        credentialPath = L"GetDelegatedAccessTokenResult|Credentials";
    }

    stringCompare.SetString(tokenXml.tag());
    bool stringMatch7 = stringCompare.ContentsEqual(L"AssumeRootResponse",true);
    if (stringMatch7 == true) {
        credentialPath = L"AssumeRootResult|Credentials";
    }

    stringCompare.SetString(credentialPath);
    bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
    if (stringMatch8 == true) {
        wprintf(L"Unsupported STS credential response.\n");
        return;
    }

    const wchar_t *accessKey = 0;
    const wchar_t *secretKey = 0;
    const wchar_t *sessionToken = 0;
    const wchar_t *expiration = 0;
    CkStringBuilderW path;
    success = path.SetString(credentialPath);
    if (success != true) {
        wprintf(L"Could not construct credential path.\n");
        return;
    }

    success = path.Append(L"|AccessKeyId");
    if (success != true) {
        wprintf(L"Could not construct credential path.\n");
        return;
    }

    accessKey = tokenXml.getChildContent(path.getAsString());
    stringCompare.SetString(accessKey);
    bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
    if ((tokenXml.get_LastMethodSuccess() != true) || (stringMatch9 == true)) {
        wprintf(L"Missing credential field AccessKeyId.\n");
        return;
    }

    success = path.SetString(credentialPath);
    if (success != true) {
        wprintf(L"Could not construct credential path.\n");
        return;
    }

    success = path.Append(L"|SecretAccessKey");
    if (success != true) {
        wprintf(L"Could not construct credential path.\n");
        return;
    }

    secretKey = tokenXml.getChildContent(path.getAsString());
    stringCompare.SetString(secretKey);
    bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
    if ((tokenXml.get_LastMethodSuccess() != true) || (stringMatch10 == true)) {
        wprintf(L"Missing credential field SecretAccessKey.\n");
        return;
    }

    success = path.SetString(credentialPath);
    if (success != true) {
        wprintf(L"Could not construct credential path.\n");
        return;
    }

    success = path.Append(L"|SessionToken");
    if (success != true) {
        wprintf(L"Could not construct credential path.\n");
        return;
    }

    sessionToken = tokenXml.getChildContent(path.getAsString());
    stringCompare.SetString(sessionToken);
    bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
    if ((tokenXml.get_LastMethodSuccess() != true) || (stringMatch11 == true)) {
        wprintf(L"Missing credential field SessionToken.\n");
        return;
    }

    success = path.SetString(credentialPath);
    if (success != true) {
        wprintf(L"Could not construct credential path.\n");
        return;
    }

    success = path.Append(L"|Expiration");
    if (success != true) {
        wprintf(L"Could not construct credential path.\n");
        return;
    }

    expiration = tokenXml.getChildContent(path.getAsString());
    stringCompare.SetString(expiration);
    bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
    if ((tokenXml.get_LastMethodSuccess() != true) || (stringMatch12 == true)) {
        wprintf(L"Missing credential field Expiration.\n");
        return;
    }

    CkDateTimeW expires;
    CkDateTimeW now;
    success = expires.SetFromTimestamp(expiration);
    if (success != true) {
        wprintf(L"Stored expiration is invalid.\n");
        return;
    }

    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        wprintf(L"Could not read current time.\n");
        return;
    }

    if (expires.DiffSeconds(now) <= 60) {
        wprintf(L"Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
        return;
    }

    CkJsonObjectW session;
    success = session.UpdateString(L"access_key",accessKey);
    if (success != true) {
        wprintf(L"Could not build normalized session.\n");
        return;
    }

    success = session.UpdateString(L"secret_key",secretKey);
    if (success != true) {
        wprintf(L"Could not build normalized session.\n");
        return;
    }

    success = session.UpdateString(L"session_token",sessionToken);
    if (success != true) {
        wprintf(L"Could not build normalized session.\n");
        return;
    }

    success = session.UpdateString(L"expiration",expiration);
    if (success != true) {
        wprintf(L"Could not build normalized session.\n");
        return;
    }

    CkJsonObjectW download;
    download.put_Strict(true);
    success = download.LoadFile(L"qa_data/aws/sts_download.json");
    if (success != true) {
        wprintf(L"Could not load download configuration.\n");
        return;
    }

    stringCompare.SetString(download.stringOf(L"bucket"));
    bool stringMatch13 = stringCompare.ContentsEqual(L"",true);
    if ((download.JsonTypeOf(L"bucket") != 1) || (stringMatch13 == true)) {
        wprintf(L"Missing bucket.\n");
        return;
    }

    stringCompare.SetString(download.stringOf(L"object_key"));
    bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
    if ((download.JsonTypeOf(L"object_key") != 1) || (stringMatch14 == true)) {
        wprintf(L"Missing object_key.\n");
        return;
    }

    CkHttpW http;
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(60);
    http.put_VerboseLogging(false);
    http.put_AwsAccessKey(session.stringOf(L"access_key"));
    http.put_AwsSecretKey(session.stringOf(L"secret_key"));
    http.put_AwsSessionToken(session.stringOf(L"session_token"));
    http.put_AwsRegion(L"us-west-2");
    http.put_AwsEndpoint(L"s3.us-west-2.amazonaws.com");
    //  Current Chilkat S3 methods use Signature Version 4.
    CkBinDataW objectData;
    success = http.S3_DownloadBd(download.stringOf(L"bucket"),download.stringOf(L"object_key"),objectData);
    if (success != true) {
        wprintf(L"S3 download failed. HTTP status: %d\n",http.get_LastStatus());
        return;
    }

    if (http.get_LastStatus() != 200) {
        wprintf(L"Unexpected S3 status; do not use the data.\n");
        return;
    }

    wprintf(L"Downloaded bytes: %d\n",objectData.get_NumBytes());
    //  Consume objectData in memory; no object contents or credentials are logged.
    wprintf(L"Example completed.\n");
    }