云oss获取临时访问凭证-方法TST

740 阅读4分钟

这是我参与8月更文挑战的第2天,活动详情查看:8月更文挑战

阿里云对象存储OSS(Object Storage Service)为您提供基于网络的数据存取服务。使用OSS,您可以通过网络随时存储和调用包括文本、图片、音视频在内的各类数据文件。

在先前的一片推文里我有写到阿里的oss云上传技术,但是,如果是外部项目,则会设计到云库的安全密钥问题,所以在这里做一下云库密钥的补充

1.后端数据代码:

主要设置介入地址,生成访问密钥,辨识访问角色,给角色自定义名称,用来区分不同的令牌,数据安全和防止一些无用信息的存储,占用存储资源,需要对角色和密钥严格把控

Java SDK为例:

package com.aliyun.sts.sample;
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;
   public **class** StsServiceSample {
    **public** static **void** main(String[] args) { 
        // STS接入地址,例如sts.cn-hangzhou.aliyuncs.com。       
        String endpoint = "<sts-endpoint>";
        // 填写步骤1生成的访问密钥AccessKey ID和AccessKey Secret。
        String AccessKeyId = "<yourAccessKeyId>"";
        String accessKeySecret = "<yourAccessKeySecret>";
        // 填写步骤3获取的角色ARN。
        String roleArn = "<yourRoleArn>";
        // 自定义角色会话名称,用来区分不同的令牌,例如可填写为SessionTest。 
        String roleSessionName = "<yourRoleSessionName>";
        // 以下Policy用于限制仅允许使用临时访问凭证向目标存储空间examplebucket上传文件。
        // 临时访问凭证最后获得的权限是步骤4设置的角色权限和该Policy设置权限的交集,即仅允许将文件上传至目标存储空间examplebucket下的exampledir目录。
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:PutObject\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:examplebucket/*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        try {
            // 添加endpoint。
            DefaultProfile.addEndpoint("", "", "Sts", endpoint);
            // 构造default profile。
            IClientProfile profile = DefaultProfile.getProfile("", AccessKeyId, accessKeySecret);
            // 构造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(3600L); // 设置临时访问凭证的有效时间为3600秒。
            final AssumeRoleResponse response = client.getAcsResponse(request);
            System.out.println("Expiration: " + response.getCredentials().getExpiration());
            System.out.println("**Access** Key Id: " + response.getCredentials().getAccessKeyId());
            System.out.println("**Access** Key Secret: " + response.getCredentials().getAccessKeySecret());
            System.out.println("**Security** Token: " + response.getCredentials().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());
        }
    }
}

2.前端密钥数据交互

前端主要是通过数据接口承接临时密钥,用来上传信息的通道,临时密钥,一般都具有实效性,需要和后端商量好实效控制以及前端的接口数据请求方式,是采用固定请求方式还是全局请求方式,这个看公司项目需求,不过我自己用的还是比较原始的笨办法,每次上传都请求,这样就不用考虑密钥的实效性,任何时候都可以请求到最新密钥。

//先引入oss基础库
import OSS from 'ali-oss';

   //创建oss类方法,并设置其请求信息(类似于请求头)
 new OSS({
   //yourRegion填写Bucket所在地域。以华东1(杭州)为例,Region填写为。
   region: 'oss-cn-hangzhou',
   //从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)/。
   accessKeyId: '',
   accessKeySecret: '',
   //从STS服务获取的安全令牌,有实效性,后端设置。
   stsToken: '',
   //填写Bucket名称,一般是自己公司的上传地址接口名。
   bucket: ''
 });

接口数据请求axios,或者fetch都可以,看自己项目技术架构设计,获取到信息分别设置oss的accessKeyId,accessKeySecret,stsToken,

3.设置完oss后的oss对象长下面这个样子

截屏2021-08-02 下午6.04.11.png

4.oss上传完成之后

将会返回阿里云库指定文件夹文件地址,阿里云的域名加上上传时自定义命名的文案名以及文件类型,改地址既可以在代码内部引用,也可直接在浏览器url当中查看地址是否正确

5.公司选择阿里云存储的优势

OSS的存储空间内部是扁平的,没有文件系统的目录等概念,所有的对象都直接隶属于其对应的存储空间。如果您想要像使用本地文件夹和磁盘那样来使用OSS存储服务,可以通过配置云存储网关来实现。通过云存储网关提供的NFS、SMB(CIFS)、iSCSI协议,OSS的存储资源会以Bucket为基础映射成本地文件夹或者磁盘。您可以通过文件读写操作访问OSS资源,无缝衔接基于POSIX和块访问协议的应用,降低应用改造和学习成本。