问题描述
使用STS临时授权阿里云对象存储OSS进行上传、下载等操作,在授权后进行资源调用时,发生以下报错:
ErrorCode: AccessDenied
ErrorMessage: Access denied by authorizer's policy.问题原因
该报错是获取STS Token代码中的Policy参数的授权问题导致,如下Java获取Token的Demo代码所示,其中的Policy设置代表Token的Policy权限设置,最终的Token权限是用户角色的授权和代码中Policy权限的交集。
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class StsServiceSample {
public static void main(String[] args) {
// 以下参数替换为实际值
String endpoint = "sts.aliyuncs.com";
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String roleArn = "<yourRoleArn>";
String roleSessionName = "<yourRoleSessionName>";
// Policy 是本次 Token 的权限上限:最终 Token 权限 = 角色授权 ∩ 此处 Policy。
// 不设置 Policy 时,Token 拥有该角色的全部权限。
String policy = "{\n"
+ " \"Version\": \"1\",\n"
+ " \"Statement\": [\n"
+ " {\n"
+ " \"Effect\": \"Allow\",\n"
+ " \"Action\": [\n"
+ " \"oss:PutObject\",\n"
+ " \"oss:GetObject\"\n"
+ " ],\n"
+ " \"Resource\": [\n"
+ " \"acs:oss:*:*:examplebucket/*\"\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ "}";
try {
DefaultProfile.addEndpoint("", "Sts", endpoint);
IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
IAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setSysMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
// setPolicy 对应上文所述的 Policy 设置,决定本次 Token 的权限上限。
request.setPolicy(policy);
request.setDurationSeconds(3600L);
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("AccessKeyId: " + response.getCredentials().getAccessKeyId());
System.out.println("SecurityToken: " + response.getCredentials().getSecurityToken());
} catch (ClientException e) {
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMessage());
}
}
}解决方案
请结合自己调用的OSS接口,检查您代码中Policy参数的授权策略,排查Policy中的授权是否正确,详情请参见STS临时授权访问OSS。
相关文档
适用于
对象存储OSS
访问控制
该文章对您有帮助吗?