阿里云STS临时授权访问OSS报NoSuchBucket
1.pom文件中添加依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-sts</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.4.6</version>
</dependency>
2写一个main方法,代码如下
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
String accessKeyId = "F-------DF";
String accessKeySecret = "====81f";
String roleArn = "acs:ram::===:role/ss";
String roleSessionName = "roleSessionName";
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(1000L); // 设置凭证有效时间
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("Expiration: " + response.getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
System.out.println("RequestId: " + response.getRequestId());
} catch (ClientException e) {
System.err.println("Failed:");
System.err.println("Error code: " + e.getErrCode());
System.err.println("Error message: " + e.getErrMsg());
System.err.println("RequestId: " + e.getRequestId());
}
3.运行上面main方法,进入catch中,Error code:NoSuchBucket 4.解决办法 由于粗心,将endpoint写为了"oss-cn-hangzhou.aliyuncs.com", 官方提供的为:“sts.cn-hangzhou.aliyuncs.com” 或者写为"sts.aliyuncs.com"
接入地址参见: https://help.aliyun.com/document_detail/66053.html?spm=a2c4g.11186623.2.21.6dc23b49cxpv4g#reference-sdg-3pv-xdb
最后: 在查找错误原因时,可以参看阿里云API错误中心,地址如下: https://error-center.aliyun.com/status/product/Oss?spm=5176.10421674.home.24.16442fcfrwtYFR
