雲賬號AccessKey擁有所有API訪問許可權,在客戶端不要直接使用,會洩露ak資訊,造成安全問題。所以使用STS方式(臨時賬號許可權)給客戶端授權。
C#版獲取STSToken
一、下載阿里SDK(aliyun-net-sdk-Core.dll和aliyun-net-sdk-Sts.dll)
下載地址:https://develop.aliyun.com/tools/sdk#/dotnet
二、把SDK引入專案,引用以下名稱空間
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;
三、準備相關賬號和策略檔案
region:OSS所屬區域,比如cn-hangzhou(杭州)等
AccessKeyID
AccessKeySecret
RoleArn
policy
以上資訊在OSS配置篇上有詳細講解,其中policy內容根據AliyunOSSTokenGeneratorRolePolicy角色的授權策略可得,可以儲存為json檔案
{ "Statement": [ { "Action": "oss:*", "Effect": "Allow", "Resource": "*" } ], "Version": "1" }
四、C#獲取STSTok的程式碼
// 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即大功告成!!!