阿里云oss——STS
阿里官方防盗链
可以防止爬虫之类的用原链接直接访问文件。
找到防盗链
设置可以访问的域名
引入SDK依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
<!--阿里临时授权-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-sts</artifactId>
</dependency>
加签名的URL --待定
参考文档:https://help.aliyun.com/document_detail/31952.html?spm=a2c4g.11186623.2.12.14357e31jWVFdc
https://github.com/aliyun/aliyun-oss-java-sdk/blob/master/src/main/java/com/aliyun/oss/OSSClient.java?spm=a2c4g.11186623.2.11.2c9c6928BHNGyb&file=OSSClient.java
阿里STS临时授权
原理
RAM控制台
ps:找不到的话搜索一下。
新增用户
配置用户权限
- 点击账号进入详情
创建权限策略
- 在左侧导航栏的权限管理菜单下,单击权限策略管理。
- 单击新建权限策略。
- 填写策略名称和备注。
- 脚本配置。
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"oss:GetObject",
"oss:PutObject",
"oss:DeleteObject",
"oss:ListParts",
"oss:AbortMultipartUpload",
"oss:ListObjects"
],
"Resource": [
"acs:oss:*:*:z****l",
"acs:oss:*:*:z****l/*"
]
}
]
}
创建角色并记录角色ARN。
- 在左侧导航栏,单击RAM角色管理。
- 单击新建RAM角色,选择可信实体类型为阿里云账号,单击下一步。
- 在新建RAM角色页面,填写RAM角色名称和备注,本示例RAM角色名称为RamOssTest。
- 选择云账号为当前云账号。
- 单击完成,之后单击为角色授权。
获取STS临时授权接口代码
/**
* 获取阿里的临时授权
*
* @param req
* @return
*/
@ApiOperation("获取阿里的临时授权")
@GetMapping("/getAliSts")
public AssumeRoleResponse.Credentials getAliSts(HttpServletRequest req) {
AssumeRoleResponse.Credentials credentials = null;
// String roleSessionName = "AliyunDMSRol--ePolicy";
String roleSessionName = "zlyftbdoss--ePolicy";
String policy = "{\n" +
" \"Statement\": [\n" +
" {\n" +
" \"Action\": [\n" +
" \"oss:GetObject\",\n" +
" \"oss:PutObject\",\n" +
" \"oss:DeleteObject\",\n" +
" \"oss:ListParts\",\n" +
" \"oss:AbortMultipartUpload\",\n" +
" \"oss:ListObjects\"\n" +
" ],\n" +
" \"Effect\": \"Allow\",\n" +
" \"Resource\": [\n" +
" \"acs:oss:*:*:z****l/*\",\n" +
" \"acs:oss:*:*:z****l\"\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"Version\": \"1\"\n" +
"}";
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); // Optional
request.setDurationSeconds(1000L); // 设置凭证有效时间
request.setProtocol(ProtocolType.HTTPS); // 必须使用HTTPS协议访问STS服务);
final AssumeRoleResponse response = client.getAcsResponse(request);
credentials = response.getCredentials();
// System.out.println("Expiration: " + credentials.getExpiration());
// System.out.println("Access Key Id: " + credentials.getAccessKeyId());
// System.out.println("Access Key Secret: " + credentials.getAccessKeySecret());
// System.out.println("Security Token: " + credentials.getSecurityToken());
// System.out.println("RequestId: " + response.getRequestId());
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
return credentials;
}
源码参数说明
-
endpoint:STS接入地址,例如sts.cn-hangzhou.aliyuncs.com
接入地址参考:https://help.aliyun.com/document_detail/66053.html?spm=a2c4g.11186623.2.21.38b23b49geOwWt#reference-sdg-3pv-xdb -
创建用户时生成的AccessKeyId、AccessKeySecret
-
RoleArn:保存的角色ARN
-
RoleSessionName:用来标识临时访问凭证的名称,建议使用不同的应用程序用户来区分。
-
Policy:在扮演角色的时候额外添加的权限限制。
测试上传图片
/**
* 阿里OSS上传文件
* @param file
* @param params
* @return
*/
@ApiOperation(value = "阿里OSS上传文件")
@PostMapping("ossUpload")
public Result ossUpload(@RequestParam("file") MultipartFile file,@RequestParam("accessKeyId") String accessKeyId,@RequestParam("accessKeySecret") String accessKeySecret,@RequestParam("securityToken") String securityToken){
System.out.println("文件信息:"+file+"============"+"其他参数:"+accessKeyId+"其他参数:"+accessKeySecret);
Result res=new Result();
String filename = file.getResource().getFilename();
//这里文件名用了uuid 防止重复,可以根据自己的需要来写
String name = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."), filename.length());
name = name.replace("-", "");
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
System.out.println("上传失败");
}
//开启ossClient;
OSSClient ossClient=new OSSClient(ossEndPoint,accessKeyId,accessKeySecret,securityToken);
//上传图片
try {
//创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(inputStream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getcontentType(name.substring(name.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + name);
// 指定上传文件操作时是否覆盖同名Object。
// 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。
// 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。
// 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。
objectMetadata.setHeader("x-oss-forbid-overwrite", "false");
//文件前缀
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
String nowDate=sdf1.format(new Date());
System.out.println("当前日期是:"+nowDate);
String filedir="tbd/"+nowDate+"/";
String objectName = filedir + name;
//上传文件
ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
// 封装 url 路径
String url = "http://" + bucketName + "." + ossEndPoint + "/" + objectName;
System.out.println(objectName);
return res.ok(url);
} catch (IOException e) {
System.out.println("错误信息:"+e.getMessage());
} finally {
ossClient.shutdown();
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return res;
}
/**
* Description: 判断OSS服务文件上传时文件的contentType
*
* @param FilenameExtension 文件后缀
* @return String
*/
public static String getcontentType(String FilenameExtension) {
if ("bmp".equalsIgnoreCase(FilenameExtension)) {
return "image/bmp";
}
if ("gif".equalsIgnoreCase(FilenameExtension)) {
return "image/gif";
}
if ("jpeg".equalsIgnoreCase(FilenameExtension) ||
"jpg".equalsIgnoreCase(FilenameExtension) ||
"png".equalsIgnoreCase(FilenameExtension)) {
return "image/jpeg";
}
if ("html".equalsIgnoreCase(FilenameExtension)) {
return "text/html";
}
if ("txt".equalsIgnoreCase(FilenameExtension)) {
return "text/plain";
}
if ("vsd".equalsIgnoreCase(FilenameExtension)) {
return "application/vnd.visio";
}
if ("pptx".equalsIgnoreCase(FilenameExtension) ||
"ppt".equalsIgnoreCase(FilenameExtension)) {
return "application/vnd.ms-powerpoint";
}
if ("docx".equalsIgnoreCase(FilenameExtension) ||
"doc".equalsIgnoreCase(FilenameExtension)) {
return "application/msword";
}
if ("xml".equalsIgnoreCase(FilenameExtension)) {
return "text/xml";
}
return "image/jpeg";
}