在 AWS 中使用 C# 获取会话令牌的示例代码如下:
using Amazon.Runtime;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
private static async Task<string> GetSessionTokenAsync()
var credentials = await GetTemporaryCredentialsAsync().ConfigureAwait(false);
return credentials.GetCredentials().SessionToken;
private static async Task<AWSCredentials> GetTemporaryCredentialsAsync()
var stsClient = new AmazonSecurityTokenServiceClient();
var assumeRoleRequest = new AssumeRoleRequest
RoleArn = "arn:aws:iam::123456789012:role/example-role",
RoleSessionName = "example-session",
DurationSeconds = 3600
var assumeRoleResponse = await stsClient.AssumeRoleAsync(assumeRoleRequest).ConfigureAwait(false);
return new SessionAWSCredentials(assumeRoleResponse.Credentials.AccessKeyId,
assumeRoleResponse.Credentials.SecretAccessKey,
assumeRoleResponse.Credentials.SessionToken);
以上代码通过 AssumeRole
API 在 AWS STS 中请求一个临时凭证,然后通过这个临时凭证获取会话令牌。