使用 C# SDK 获取 AWS 调用者身份

Get AWS caller Identity with C# SDK

当我使用 aws cli 执行此操作时,i.ex。在 fargate 任务中,我可以看到我的应用程序将要使用的 UserId

aws sts get-caller-identity

在控制台上有这个输出

{
    "Arn": "arn:aws:sts::643518765421:assumed-role/url_process_role/6ae81f92-66f3-30de-1eaa-3a7d1902bad9",
    "UserId": "ARDYOAZLVOAQXTT5ZXTV4:4ea81f97-66f3-40de-beaa-3a7d1902bad9",
    "Account": "692438514791"
}

我想获得相同的信息,但使用的是 C# SDK。我尝试使用 this doc 中公开的方法,但我可以看到一些与帐户相关的详细信息,但看不到分配的 UserId

到目前为止我已经尝试过这个但是当 运行 在 Fargate 任务中时我看不到任何配置文件。

var awsChain = new Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain();
System.Console.WriteLine($"Found {awsChain.ListProfiles().Count} AWS profiles.");

我的最终目标是获取它并添加到使用 Fargate 处理的某些任务中,以便在出现故障时在数据库中保存相关 ID,并轻松找到 Fargate 日志流。

IAmazonSecurityTokenService 在使用 .netcore 执行时将提供相同的信息。请注意,上面的示例仅在 AWS 域内有效,因为如果从开发机器进行测试,则端点不公开可用。

var getSessionTokenRequest = new GetSessionTokenRequest
{
    DurationSeconds = 7200
};
var stsClient = hostContext.Configuration.GetAWSOptions().CreateServiceClient<IAmazonSecurityTokenService>();

var iden = stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest { }).Result;
System.Console.WriteLine($"A={iden.Account} ARN={iden.Arn} U={iden.UserId}");