返回
STS临时授权访问OSS文件-java实现
见解分享
2023-11-20 15:05:18
概述
云上临时授权访问OSS文件需要完成以下步骤:
- 创建用户。
- 创建权限策略。
- 创建RAM角色并授权上述步骤。
其中,创建用户和创建权限策略通过RAM控制台完成,创建RAM角色并授权可以通过RAM控制台或RAM API完成。本文档将重点介绍通过Java代码完成临时授权访问OSS文件。
Java代码实现
1. 导入必要的包
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.sts.ClientException;
import com.aliyun.sts.ServiceSettings;
import com.aliyun.sts.STS;
import com.aliyun.sts.model.AssumeRoleRequest;
import com.aliyun.sts.model.AssumeRoleResult;
import com.aliyun.sts.model.Credentials;
import java.io.ByteArrayInputStream;
import java.util.Date;
public class AssumeRoleSample {
public static void main(String[] args) {
String regionId = "your-region-id";
String accessKeyId = "your-access-key-id";
String accessKeySecret = "your-access-key-secret";
String roleArn = "your-role-arn";
String bucketName = "your-bucket-name";
String objectKey = "your-object-key";
// 创建STS Client。
ServiceSettings serviceSettings =
ServiceSettings.builder()
.endpoint("sts." + regionId + ".aliyuncs.com") // 设置STS Endpoint。
.build();
STS stsClient = STS.create(accessKeyId, accessKeySecret, serviceSettings);
// 构造AssumeRole请求对象。
AssumeRoleRequest assumeRoleRequest =
new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("your-session-name");
// 临时授权访问OSS文件。
AssumeRoleResult assumeRoleResult = stsClient.assumeRole(assumeRoleRequest);
Credentials credentials = assumeRoleResult.getCredentials();
// 创建OSSClient实例。
OSS ossClient =
new OSSClientBuilder()
.build(
regionId,
credentials.getAccessKeyId(),
credentials.getAccessKeySecret(),
credentials.getSecurityToken());
// 上传文件。
String content = "Hello STS";
ossClient.putObject(
bucketName,
objectKey,
new ByteArrayInputStream(content.getBytes()),
new PutObjectRequest(bucketName, objectKey));
System.out.println("Object uploaded successfully.");
// 获取文件。
OSSObject ossObject = ossClient.getObject(bucketName, objectKey);
String fileContent = new String(ossObject.getObjectContent().readAllBytes());
System.out.println("Object content: " + fileContent);
// 关闭OSSClient。
ossClient.shutdown();
}
}
运行示例
-
运行示例代码之前,请确保您已经完成了以下步骤:
- 创建用户。
- 创建权限策略。
- 创建RAM角色并授权上述步骤。
-
将上述代码中的
<your-region-id>
、<your-access-key-id>
、<your-access-key-secret>
、<your-role-arn>
、<your-bucket-name>
和<your-object-key>
替换为您的实际值。 -
编译并运行Java代码。
-
运行成功后,您可以在OSS控制台的存储空间中找到上传的文件。
注意事项
- 临时授权凭证的有效期为1小时。如果您需要使用临时授权凭证访问OSS文件超过1小时,您需要重新获取临时授权凭证。
- 临时授权凭证只能用于访问授权的资源。例如,如果您创建了一个临时授权凭证用于访问OSS存储空间中的特定文件夹,那么您只能使用该临时授权凭证访问该文件夹中的文件。
- 临时授权凭证是安全的。即使有人获得了您的临时授权凭证,他们也无法访问您的OSS存储空间中的其他资源。