本文简要介绍如何构建一个 .NET SDK 的示例。

using System;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Sts.Model.V20150401;
namespace StsNetSdkDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            const string REGIONID = "cn-shanghai";
            const string ENDPOINT = "sts.cn-shanghai.aliyuncs.com";
            // 构建一个阿里云 Client, 用于发起请求
            // 构建阿里云 Client 时需要设置 access key ID 和 access key secret
            DefaultProfile.AddEndpoint(REGIONID, REGIONID, "Sts", ENDPOINT);
            IClientProfile profile = DefaultProfile.GetProfile(REGIONID, "<access-key-id>", "<access-key-secret>");
            DefaultAcsClient client = new DefaultAcsClient(profile);
            // 构建 AssumeRole 请求
            AssumeRoleRequest request = new AssumeRoleRequest();
            request.AcceptFormat = FormatType.JSON;
            // 指定角色 ARN
            request.RoleArn = "<role-arn>";
            request.RoleSessionName = "<role-session-name>";
            // 设置 token 有效期,可选参数,默认 3600 秒;
            // request.DurationSeconds = 3600;
            // 设置 token 的附加权限策略;在获取 token 时,通过额外设置一个权限策略进一步减小 Token 的权限;
            // request.Policy="<policy-content>"
            try
            {
                AssumeRoleResponse response = client.GetAcsResponse(request);
                Console.WriteLine("AccessKeyId: " + response.Credentials.AccessKeyId);
                Console.WriteLine("AccessKeySecret: " + response.Credentials.AccessKeySecret);
                Console.WriteLine("SecurityToken: " + response.Credentials.SecurityToken);
                //Token 过期时间;服务器返回 UTC 时间,这里转换成北京时间显示;
                Console.WriteLine("Expiration: " + DateTime.Parse(response.Credentials.Expiration).ToLocalTime());
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
            }
            Console.ReadLine();
        }
    }
}
说明
  • STS 各区域的 endpoint 请参考:接入地址
  • AssumeRole 接口相关信息,请参考:AssumeRole