调用GetCallerIdentityAsync遇ClientName空值错误,如何指定ClientName?
问题
使用AWS SDK官方文档示例代码尝试扮演IAM角色时,调用GetCallerIdentityAsync方法抛出错误:
Value cannot be null. Parameter name: Options property cannot be empty: ClientName
相关代码示例如下:
using System; using System.Threading.Tasks; using Amazon; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; namespace AssumeRoleExample { class AssumeRole { /// <summary> /// This example shows how to use the AWS Security Token /// Service (AWS STS) to assume an IAM role. /// /// NOTE: It is important that the role that will be assumed has a /// trust relationship with the account that will assume the role. /// /// Before you run the example, you need to create the role you want to /// assume and have it trust the IAM account that will assume that role. /// </summary> private static readonly RegionEndpoint REGION = RegionEndpoint.USWest2; static async Task Main() { // Create the SecurityToken client and then display the identity of the // default user. var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole"; var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION); // Get and display the information about the identity of the default user. var callerIdRequest = new GetCallerIdentityRequest(); var caller = await client.GetCallerIdentityAsync(callerIdRequest); Console.WriteLine($"Original Caller: {caller.Arn}"); // Create the request to use with the AssumeRoleAsync call. var assumeRoleReq = new AssumeRoleRequest() { DurationSeconds = 1600, RoleSessionName = "Session1", RoleArn = roleArnToAssume }; var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq); // Now create a new client based on the credentials of the caller assuming the role. var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials); // Get and display information about the caller that has assumed the defined role. var caller2 = await client2.GetCallerIdentityAsync(callerIdRequest); Console.WriteLine($"AssumedRole Caller: {caller2.Arn}"); } } }
已通过在线控制台创建IAM用户,并按照文档委托了使用特定服务的对应权限,请问该如何指定ClientName?目前未找到相关公开资料。
解决方案
这个错误是因为创建第二个AmazonSecurityTokenServiceClient实例时,仅传入凭证但未正确初始化客户端配置,导致ClientName属性缺失。可以通过以下两种方式解决:
方式一:显式指定配置选项
创建客户端时,同时传入凭证、区域并设置自定义ClientName:var client2 = new AmazonSecurityTokenServiceClient( assumeRoleRes.Credentials, new AmazonSecurityTokenServiceConfig { RegionEndpoint = REGION, ClientName = "STSAssumedRoleClient" });方式二:使用带区域的构造函数
直接调用同时接收凭证和区域的构造函数,SDK会自动填充必要的配置(包括默认ClientName):var client2 = new AmazonSecurityTokenServiceClient(assumeRoleRes.Credentials, REGION);
原代码中创建client2时仅传入凭证参数,未指定区域或配置,导致SDK内部初始化时ClientName为空触发异常。第二种方式更简洁,符合SDK常规使用习惯,优先推荐。
内容的提问来源于stack exchange,提问作者Leventogenna
相关产品推荐
相关产品推荐

