全部产品
阿里云办公

示例

更新时间:2018-01-30 09:45:37

  1. using System;
  2. using Aliyun.Acs.Core;
  3. using Aliyun.Acs.Core.Profile;
  4. using Aliyun.Acs.Core.Http;
  5. using Aliyun.Acs.Sts.Model.V20150401;
  6. namespace StsNetSdkDemo
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. const string REGIONID = "cn-shanghai";
  13. const string ENDPOINT = "sts.cn-shanghai.aliyuncs.com";
  14. // 构建一个 Aliyun Client, 用于发起请求
  15. // 构建Aliyun Client时需要设置AccessKeyId和AccessKeySevcret
  16. DefaultProfile.AddEndpoint(REGIONID, REGIONID, "Sts", ENDPOINT);
  17. IClientProfile profile = DefaultProfile.GetProfile(REGIONID, "<access-key-id>", "<access-key-secret>");
  18. DefaultAcsClient client = new DefaultAcsClient(profile);
  19. // 构造AssumeRole请求
  20. AssumeRoleRequest request = new AssumeRoleRequest();
  21. request.AcceptFormat = FormatType.JSON;
  22. // 指定角色Arn
  23. request.RoleArn = "<role-arn>";
  24. request.RoleSessionName = "<role-session-name>";
  25. // 可以设置Token有效期,可选参数,默认3600秒;
  26. // request.DurationSeconds = 3600;
  27. // 可以设置Token的附加Policy,可以在获取Token时,通过额外设置一个Policy进一步减小Token的权限;
  28. // request.Policy="<policy-content>"
  29. try
  30. {
  31. AssumeRoleResponse response = client.GetAcsResponse(request);
  32. Console.WriteLine("AccessKeyId: " + response.Credentials.AccessKeyId);
  33. Console.WriteLine("AccessKeySecret: " + response.Credentials.AccessKeySecret);
  34. Console.WriteLine("SecurityToken: " + response.Credentials.SecurityToken);
  35. //Token过期时间;服务器返回UTC时间,这里转换成北京时间显示;
  36. Console.WriteLine("Expiration: " + DateTime.Parse(response.Credentials.Expiration).ToLocalTime());
  37. }
  38. catch (Exception ex)
  39. {
  40. Console.Write(ex.ToString());
  41. }
  42. Console.ReadLine();
  43. }
  44. }
  45. }