package com.chuanyi.ecard.utils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.chuanyi.ecard.exception.RequestFailException;
/**
* oss 授权工具
* @author Admin
*
*/
public class OssStsUtils {
private static String endpoint = "sts.aliyuncs.com";
private static String accessKeyId = "***";
private static String accessKeySecret = "***";
private static String roleArn = "***";
/**
* 获取 admin oss的 临时凭证
* @param roleSessionName 表示当前零时凭证给谁用,一般是用户名
* @return
*/
public static AssumeRoleResponse.Credentials getAdminOssCredentials(String roleSessionName) {
String policy = "{\r\n" +
" \"Statement\": [{\r\n" +
" \"Action\": \"oss:*\",\r\n" +
" \"Effect\": \"Allow\",\r\n" +
" \"Resource\": [\"acs:oss:*:*:test-tfmm\", \"acs:oss:*:*:test-tfmm/*\"]\r\n" +
" }],\r\n" +
" \"Version\": \"1\"\r\n" +
"}";
long expired = 1800L;
return getOssRoleResponse(endpoint, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy, expired).getCredentials();
}
private static AssumeRoleResponse getOssRoleResponse(String endpoint,String accessKeyId,String accessKeySecret,String roleArn,String roleSessionName ,String policy,long expired ) {
try {
// 添加endpoint(直接使用STS endpoint,前两个参数留空,无需添加region ID)
DefaultProfile.addEndpoint("", "", "Sts", endpoint);
// 构造default profile(参数留空,无需添加region ID)
IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
// 用profile构造client
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
request.setPolicy(policy); // 若policy为空,则用户将获得该角色下所有权限
request.setDurationSeconds( expired ); // 设置凭证有效时间
final AssumeRoleResponse response = client.getAcsResponse(request);
return response;
} catch (ClientException e) {
throw new RequestFailException( e.getLocalizedMessage() );
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
需要注意的 是 endpoint 不是 oss 的 endpoint 而是 sts 的 endpoint 。 如果是 用好了 oss 的 endpoint 或一直报错 buket not exits ;