oss 获取临时凭证 工具类
Posted cxygg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了oss 获取临时凭证 工具类相关的知识,希望对你有一定的参考价值。
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 = "{ " + " "Statement": [{ " + " "Action": "oss:*", " + " "Effect": "Allow", " + " "Resource": ["acs:oss:*:*:test-tfmm", "acs:oss:*:*:test-tfmm/*"] " + " }], " + " "Version": "1" " + "}"; 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() ); } } }
需要注意的 是 endpoint 不是 oss 的 endpoint 而是 sts 的 endpoint 。 如果是 用好了 oss 的 endpoint 或一直报错 buket not exits ;
以上是关于oss 获取临时凭证 工具类的主要内容,如果未能解决你的问题,请参考以下文章