本文简要介绍了.NET SDK的安装并提供一个简单的操作示例。

.NET SDK的安装

安装包下载地址:

说明 STS已经接入NuGet,详情请参见STS NuGet

.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时需要设置AccessKey ID和AccessKey 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();
        }
    }
}
说明