雲帳號AccessKey擁有全部API訪問權限,在客戶端不要直接使用,會泄露ak信息,形成安全問題。因此使用STS方式(臨時帳號權限)給客戶端受權。javascript
C#版獲取STSTokenjava
1、下載阿里SDK(aliyun-net-sdk-Core.dll和aliyun-net-sdk-Sts.dll)json
下載地址:https://develop.aliyun.com/tools/sdk#/dotnet安全
2、把SDK引入項目,引用如下命名空間spa
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Sts.Model.V20150401;code
3、準備相關帳號和策略文件blog
region:OSS所屬區域,好比cn-hangzhou(杭州)等
AccessKeyID
AccessKeySecret
RoleArn
policytoken
以上信息在OSS配置篇上有詳細講解,其中policy內容根據AliyunOSSTokenGeneratorRolePolicy角色的受權策略可得,能夠保存爲json文件ip
{ "Statement": [ { "Action": "oss:*", "Effect": "Allow", "Resource": "*" } ], "Version": "1" }
4、C#獲取STSTok的代碼generator
// GET: /STS/Token public ActionResult Token() { string region = "cn-hangzhou"; string AccessKeyID = "LTAI5sruyeiwWDBx"; string AccessKeySecret = "EpFKkoeenidFHYAs3iIHYisAw"; string RoleArn = "acs:ram::163898893340737:role/aliyunosstokengeneratorrole"; string roleSessionName = "alice-001"; long durationSeconds = 3600; string PolicyFile = System.IO.File.ReadAllText(Request.MapPath("/policy.json")); try { // 建立一個 Aliyun Acs Client, 用於發起 OpenAPI 請求 IClientProfile profile = DefaultProfile.GetProfile(region, AccessKeyID, AccessKeySecret); DefaultAcsClient client = new DefaultAcsClient(profile); // 建立一個 AssumeRoleRequest 並設置請求參數 AssumeRoleRequest request = new AssumeRoleRequest(); request.Method = MethodType.POST; request.RoleArn = RoleArn; request.RoleSessionName = roleSessionName; request.Policy = PolicyFile; request.DurationSeconds = durationSeconds; // 發起請求,並獲得response AssumeRoleResponse stsResponse = client.GetAcsResponse(request); var Credentials = stsResponse.Credentials; //返回Token return Json(new { status = 200, AccessKeyId = Credentials.AccessKeyId, AccessKeySecret = Credentials.AccessKeySecret, Expiration = Credentials.Expiration, SecurityToken = Credentials.SecurityToken }, JsonRequestBehavior.AllowGet); } catch (ClientException e) { return Content(e.Message); } }
使用/STS/Token便可獲取STSToken,其結果示例爲:
{"status":200,"AccessKeyId":"STS.NHvFVYDPf2dmTRiPCv5ujnTbh","AccessKeySecret":"EanhX5L1na3jTDBTGSGALqcYm9qrB8s997tynnB8BVWi","Expiration":"2018-09-18T15:14:10Z","SecurityToken":"CAIShwJ1q6Ft5B2yfSjIr4vDDeztqY9HhaaGVnTYtEMjOfpGgZHJijz2IHtIenlvCO0YsfU+nWFW6/wdlqB6T55OSAmcNZIoZRTEcLXlMeT7oMWQweEurv/MQBqyaXPS2MvVfJ+OLrf0ceusbFbpjzJ6xaCAGxypQ12iN+/m6/Ngdc9FHHPPD1x8CcxROxFppeIDKHLVLozNCBPxhXfKB0ca0WgVy0EHsPrknZzBsUuA1wamkrBO+L6ceMb0M5NeW75kSMqw0eBMca7M7TVd8RAi9t0t1/AaqWiW44/CUggIskvbabXOgdRrLR5kYK8hALJDr/X6mvB+t/bai4Pt0RFJMPH83N428l48qhqAARtekq0AI7oT1jdeRLnqijTNR98Wdyvd4jzYZa8UipExR/D00ZEvmWY9zlC4kKqjfDYn2nkPhN3k8vcV//YuLYv72EhSG4GO/sBQqx8YE/FMkNdNYfMPXZY6C1jWqOAhqb97WhQP+MpXNQh7dic1x+6N//OzR2w5Dx0TszDoWRtv"}
到這裏,獲取STSToken即大功告成!!!