RAM STS 创建和使用
第一步:创建空的 RAM 子账号 testaliyun
第二步:创建角色 xueba
第三步:创建一个访问 OSS 策略,xuebajun
策略请改成您自己的,我这个策略的效果就是,能够上传、下载、list 分片、中断分片上传,其他策略请参考我的 RAM 合集文章
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"oss:ListParts",
"oss:AbortMultipartUpload",
"oss:PutObject",
"oss:GetObject"
],
"Resource": [
"acs:oss:*:*:testbucket"
],
{
"Effect": "Allow",
"Action": [
"oss:ListParts",
"oss:AbortMultipartUpload",
"oss:PutObject",
"oss:GetObject"
],
"Resource": [
"acs:oss:*:*:testbucket/*"
]
}
}
]
}
第四步:最后给 RAM 账号 testaliyun 授权一个调用角色的权限,就可以调用角色 xueba 了。
生成 STS 代码
提供一段 java 请求 STS 的方法可以参考
package oss;
import com.aliyun.oss.ClientConfiguration;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
public class AssumeRole {
/*
* 描述:生成 STS 的方式上传
*
*/
public void MakeSTSToken(String accessKeyId, String accessKeySecret, String roleArn,String roleName) throws ClientException {
ClientConfiguration conf = new ClientConfiguration();
conf.setMaxConnections(200);
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
AssumeRoleResponse response = assumeRole(client, roleArn,roleName);
AssumeRoleResponse.Credentials credentials = response.getCredentials();
System.out.println(credentials.getAccessKeyId() + "\n" + credentials.getAccessKeySecret() + "\n"
+ credentials.getSecurityToken() + "\n" + credentials.getExpiration());
}
private static AssumeRoleResponse assumeRole(DefaultAcsClient client, String roleArn,String roleName) throws ClientException {
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setVersion("2015-04-01");
request.setMethod(MethodType.POST);
request.setProtocol(ProtocolType.HTTPS);
request.setDurationSeconds(3600L);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleName);
return client.getAcsResponse(request);
}
}