OSS 视频点播临时授权

xiaoxiao2025-08-14  5

OSS 视频点播临时授权

一、必要jar包二、参数配置三、权限规则四、代码实现 项目中有集成阿里云的OSS对象存储和视频点播,其中有使用到STS(临时授权访问),下面对sts的集成实现流程及其注意事项进行总结。 在项目中,我们使用的是maven仓库,SpringBoot框架

一、必要jar包

这里我使用的是maven,在pom.xml文件中引入

<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.3.0</version> </dependency>

二、参数配置

配置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<Map<String, String>> getALiYunOSSToken(HttpServletRequest request){ //此处传递用户id,在项目中我们封装了统一验证token和获取用户id的方法,在使用过程中需要根据自己的业务需求进行参数传递 String userId = “此处传递userId,或其他用户标志”; try { // 获取临时授权token AssumeRoleResponse assumeRoleResponse = ossService.assumeRole(userId); // 构造返回参数 Map<String,String> map = new HashMap<String,String>(); // 账号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 ActionResult<>(map); } catch (ClientException e) { e.printStackTrace(); return new ActionResult<>(2, "获取阿里oss token失败,服务器内部错误!错误码:" + e.getErrCode() + ";错误信息:" + e.getErrMsg()); } } }

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

转载请注明原文地址: https://www.6miu.com/read-5034809.html

最新回复(0)