这里我使用的是maven,在pom.xml文件中引入
com.aliyun.oss
aliyun-sdk-oss
3.3.0
配置application.properties文件
#region
aliyun.oss.REGION_CN_HANGZHOU=cn-hangzhou
#阿里云oss服务,下面两个参数需要在阿里服务器配置访问控制RAM,为用户、角色分配相应权限
aliyun.oss.AccessKeyID=********
aliyun.oss.AccessKeySecret=*******
#当前STS API版本
aliyun.oss.STS_API_VERSION=2015-04-01
#角色,同样在阿里云用户管理可以查看
aliyun.oss.RoleArn=acs:ram::****************
#定义权限规则,这里我权限规则写在一个文件中,在实际运用中也可以将其直接写在代码中
aliyun.oss.PolicyFile=bucket_read_write_policy.txt
#token有效时长
aliyun.oss.TokenExpireTime=30
#外网访问地址
aliyun.oss.service=http://localhost/项目名/
bucket_read_write_policy.txt
{
"Statement": [
{
"Action": [
"oss:GetObject",
"oss:PutObject",
"oss:DeleteObject",
"oss:ListParts",
"oss:AbortMultipartUpload",
"oss:ListObjects",
"vod:*"// 该配置是视频点播的权限,只需要集成OSS sts时可将其去除
],
"Effect": "Allow",
//可访问的资源,如果只允许访问部分资源,可用通配符指定文件例如"acs:oss:*:*:qqq-qqq/*", "acs:oss:*:*:qqq-qqq"
"Resource": ["*"]
}
],
"Version": "1"
}
Controller层
package com.lxzx.lxzaixian.controller.system;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.lxzx.lxzaixian.common.ActionResult;
import com.lxzx.lxzaixian.common.SystemContext;
import com.lxzx.lxzaixian.service.system.StsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("sts")
public class StsController {
@Autowired
private StsService ossService;
@ApiOperation(value = "获取OSS临时权限")
@GetMapping(value="/getALiYunOSSToken")
public ActionResult
Service层
package com.lxzx.lxzaixian.service.system.impl;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.lxzx.lxzaixian.service.system.StsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
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;
@Service
public class StsServiceImpl implements StsService {
@Value("${aliyun.oss.REGION_CN_HANGZHOU}")
private String aliyunOssREGION_CN_HANGZHOU;
@Value("${aliyun.oss.AccessKeyID}")
private String aliyunOssAccessKeyID;
@Value("${aliyun.oss.AccessKeySecret}")
private String aliyunOssAccessKeySecret;
@Value("${aliyun.oss.STS_API_VERSION}")
private String aliyunOssSTS_API_VERSION;
@Value("${aliyun.oss.RoleArn}")
private String aliyunOssRoleArn;
@Value("${aliyun.oss.PolicyFile}")
private String aliyunOssPolicyFile;
@Value("${aliyun.oss.TokenExpireTime}")
private int aliyunOssTokenExpireTime;
/**
* 获取阿里云oss sts临时权限
* @return 令牌
*/
@Override
public AssumeRoleResponse assumeRole(String roleSessionName) throws ClientException {
// 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
// 只有 RAM用户(子账号)才能调用 AssumeRole 接口
// 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
//首先在RAM控制台创建一个RAM用户,并为这个用户创建AccessKeys
IClientProfile profile = DefaultProfile.getProfile(aliyunOssREGION_CN_HANGZHOU, aliyunOssAccessKeyID,
aliyunOssAccessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
// 创建一个 AssumeRoleRequest 并设置请求参数
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setVersion(aliyunOssSTS_API_VERSION);
request.setMethod(MethodType.POST);
// 此处必须为 HTTPS
request.setProtocol(ProtocolType.HTTPS);
// RoleArn 需要在 RAM 控制台上获取
request.setRoleArn(aliyunOssRoleArn);
// RoleSessionName 是临时Token的会话名称,自己指定用于标识你的用户,主要用于审计,或者用于区分Token颁发给谁
// 但是注意RoleSessionName的长度和规则,不要有空格,只能有'-' '_' 字母和数字等字符
// 具体规则请参考API文档中的格式要求
request.setRoleSessionName(roleSessionName);
// 授权策略
request.setPolicy(readJson(aliyunOssPolicyFile));
// 设置token时间
request.setDurationSeconds(aliyunOssTokenExpireTime * 120L);
// 发起请求,并得到response
return client.getAcsResponse(request);
}
@Override
public String readJson(String path) {
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
// 返回值,使用StringBuffer
StringBuffer data = new StringBuffer();
try {
inputStream = new ClassPathResource(path).getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
// 每次读取文件的缓存
String temp = null;
while ((temp = reader.readLine()) != null) {
data.append(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭文件流
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data.toString();
}
}
该实现大部分参考于
https://blog.csdn.net/qq_38789941/article/details/81097358