欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

阿里云oss存储使用sts时JAVA后台实现

程序员文章站 2022-07-10 18:06:52
...

关于 权限管理概念 及详细文档,请参考官网进行查看

https://help.aliyun.com/document_detail/31929.html?spm=a2c4g.11186623.6.665.qURFTX

pom文件中引入

        <!-- 阿里云对象存储 -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- 阿里云对象存储 -->

在配置文件中添加 oss 相关配置

阿里云oss存储使用sts时JAVA后台实现

添加授权策略:bucket_read_write_policy.txt

{
  "Statement": [
    {
      "Action": [
        "oss:GetObject",
        "oss:PutObject",
        "oss:DeleteObject",
        "oss:ListParts",
        "oss:AbortMultipartUpload",
        "oss:ListObjects"
      ],
      "Effect": "Allow",
      "Resource": ["acs:oss:*:*:qqq-qqq/*", "acs:oss:*:*:qqq-qqq"]
    }
  ],
  "Version": "1"
}

后台创建服务

package com.baojian.zhang.api.servic;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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;

/**
 * 
 * 功能:获取阿里云oss服务<br>
 * 作者:张tt<br>
 * 时间:2018年7月18日<br>
 * 版本:1.0<br>
 *
 */
@Service
public class ALiYunOSSService {
	
	@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临时权限
	 * @param roleSessionName
	 * 			临时Token的会话名称
	 * @return	令牌
	 * @throws ClientException
	 */
	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 * 60L);
		// 发起请求,并得到response
		return client.getAcsResponse(request);
	}
	
	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();
	}
}

编写接口

@RequestMapping(value="/getALiYunOSSToken", method = RequestMethod.GET)
	@ApiOperation(value = "获取阿里云token")
	public BaseVO<Map<String, String>> getALiYunOSSToken(
			@RequestParam(value = "cardNumber", required = true) @ApiParam(name = "cardNumber", value="用户名", required = true) String cardNumber,
			@RequestParam(value = "tokenName", required = true) @ApiParam(name = "tokenName", value = "android传入android,ios传入ios", required = true) String tokenName){
		
		if (StringUtils.isBlank(cardNumber) || StringUtils.isBlank(tokenName)) {
			return new BaseVO<Map<String, String>>(2, "cardNumber或tokenName不能为空!");
		}
		
		try {
			// 获取临时授权token
			AssumeRoleResponse assumeRoleResponse = ossService.assumeRole(tokenName);
			// 构造返回参数
			Map<String,String> map = new HashMap<String,String>();
			// 根节点
			map.put("endPoint", aliyunOssEndpoint);
			// 空间名称
			map.put("bucketName", aliyunOssBucketName);
			// 账号ID
			map.put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId());
			// 密码
			map.put("accessKeySecret", assumeRoleResponse.getCredentials().getAccessKeySecret());
			// token
			map.put("securityToken", assumeRoleResponse.getCredentials().getSecurityToken());
			// 有效时间
			map.put("expiration", assumeRoleResponse.getCredentials().getExpiration());
			
			return new BaseVO<Map<String,String>>(1, "获取阿里 oss token 成功!", map);
		} catch (ClientException e) {
			e.printStackTrace();
			return new BaseVO<Map<String, String>>(2,
					"获取阿里oss token失败,服务器内部错误!错误码:" + e.getErrCode() + ";错误信息:" + e.getErrMsg());
		}
		
	}

 

相关标签: OSS