今天使用OSS的STS来权限控制某个目录,中途遇到了很多坑,这里就不细说,网上有很多相关的文章,但是完整的流程我没有找到,这里根据自己的踩坑之路,进行完整的总结,详细描述整个流程。
1、首先需要登录阿里云账号,到控制台的"访问控制",首先添加一个STS用户。
点击确定后,记录下key和秘钥。
2、新建RAM角色
3、给上面添加RAM角色添加权限,同时记录下ARN,后面需要用到(比较关键的一步,我就是这里掉坑里了)
4、java的pom中引入相关jar进行使用。
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.4.6</version>
</dependency>
使用代码:
public void authOssDir(String ossPath) {
IClientProfile profile = DefaultProfile.getProfile(regionId
, << STS_ACCESS_KEY_ID >> , <<STS_ACCESS_KEY_SECRET >>);
// 用profile构造client
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setSysEndpoint("sts.aliyuncs.com");
request.setSysMethod(MethodType.POST);
request.setRoleArn( << STS_ROLE_ARN >>);
String roleSessionName = "oss-policy-" + RandomUtil.randomString(4);
request.setRoleSessionName(roleSessionName);
// Optional
String policy = "{\n" +
" \"Statement\": [\n" +
" {\n" +
" \"Action\": [\n" +
" \"oss:GetObject\",\n" +
" \"oss:PutObject\",\n" +
" \"oss:ListObjects\"\n" +
" ],\n" +
" \"Effect\": \"Allow\",\n" +
" \"Resource\": [\"acs:oss:*:*:" + <<BUCKET-NAME>> + "/" + ossPath + "/*\", \"acs:oss:*:*:<<BUCKET-NAME>>\"]\n" +
" }\n" +
" ],\n" +
" \"Version\": \"1\"\n" +
"}";
request.setPolicy(policy);
// 临时凭证的有效期,单位是s,最小为900,最大为3600
request.setDurationSeconds(900L);
final AssumeRoleResponse response = client.getAcsResponse(request);
// 这里的时间是utf时间,需要转换
String expiration = convertTime(response.getCredentials().getExpiration());
String accessKeyId = response.getCredentials().getAccessKeyId();
String accessKeySecret = response.getCredentials().getAccessKeySecret();
String securityToken = response.getCredentials().getSecurityToken();
log.debug("Expiration: " + expiration);
log.debug("Access Key Id: " + accessKeyId);
log.debug("Access Key Secret: " + accessKeySecret);
log.debug("Security Token: " + securityToken);
log.debug("RequestId: " + response.getRequestId());
}
/**
* UTC时间转换为当地时间
*
* @param utcTime UTC时间
* @return 北京时间
*/
private static String convertTime(String utcTime) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
//设置时区UTC
df.setTimeZone(TimeZone.getTimeZone("UTC"));
//格式化,转当地时区时间
Date after = null;
try {
after = df.parse(utcTime);
} catch (ParseException e) {
e.printStackTrace();
}
return DateUtils.formatDateTime(after);
}