云账号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 = ;
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 = ,
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即大功告成!!!