2
votes

On the command line I'm able to run this AWS CLI command to get the AWS UserId being used on my local machine

$ aws sts get-caller-identity
{
    "UserId": "123456789:john.doe",
    "Account": "123456789",
    "Arn": "arn:aws:sts::123456789:federated-user/john.doe"
}

I now need to get this same information (specifically the UserId) from the AWS SDK for C++. I've been trying to use the aws/sts/STSClient.h library like so

#include <aws/core/auth/AWSCredentialsProvider.h>
#include <aws/sts/STSClient.h>
#include <aws/sts/model/GetAccessKeyInfoRequest.h>
#include <aws/sts/model/GetCallerIdentityRequest.h>

#include <array>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <stdexcept>

#include <unistd.h>

void test() {

    Aws::STS::STSClient stsClient;

    Aws::STS::Model::GetCallerIdentityRequest getCallerIdentityRequest;

    Aws::STS::Model::GetCallerIdentityOutcome callerIdentityOutcome =
    stsClient.GetCallerIdentity(getCallerIdentityRequest);

    if (callerIdentityOutcome.IsSuccess())
    {
        Aws::STS::Model::GetCallerIdentityResult callerIdentityResult = callerIdentityOutcome.GetResult();

        Aws::String const &userIdAWSString = callerIdentityResult.GetUserId();
        std::string        userId(userIdAWSString.c_str(), userIdAWSString.size());

        std::cout << "userId: " << userId << std::endl;
    }
    else
    {
        std::cout << "callerIdentityOutcome: Failed to retrieve STS GetCallerIdentityRequest" << std::endl;
    }
}

But I keep getting an exception when calling Aws::STS::STSClient stsClient;

external/aws/aws-cpp-sdk-core/source/config/AWSProfileConfigLoader.cpp:498: Aws::Config::Profile Aws::Config::GetCachedConfigProfile(const Aws::String &): Assertion `s_configManager' failed.

Does anyone know what I'm doing wrong?

Update:

I'm even able to do it using the Boto3 library for AWS's Python SDK

>>> import boto3
>>> client = boto3.client('sts')
>>> response = client.get_caller_identity()
>>> print(response)
{u'Account': '123456789', u'UserId': '123456789:john.doe', 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '80e471ba-384a-4b6a-a5b8-f754f16c3a23', 'HTTPHeaders': {'x-amzn-requestid': '80e471ba-384a-4b6a-a5b8-f754f16c3a23', 'date': 'Fri, 27 Dec 2019 17:13:27 GMT', 'content-length': '431', 'content-type': 'text/xml'}}, u'Arn': 'arn:aws:sts::123456789:federated-user/john.doe'}

Why is this so hard to do in C++?

1

1 Answers

4
votes

Have you initialized the SDK correctly? Here's a skeleton:

#include <aws/core/Aws.h>
int main(int argc, char** argv)
{
   Aws::SDKOptions options;
   Aws::InitAPI(options);

   // make your SDK calls here

   Aws::ShutdownAPI(options);
   return 0;
}