首页 > 解决方案 > 使用 C# SDK 获取 AWS 调用者身份

问题描述

当我使用 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。我尝试使用此文档中公开的方法,但我可以看到一些与帐户相关的详细信息,但看不到UserId分配的。

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

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

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

标签: c#.net.net-coreaws-sdk

解决方案


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}");

推荐阅读