美文网首页
阿里云OSS代码集

阿里云OSS代码集

作者: AC编程 | 来源:发表于2022-06-08 18:37 被阅读0次

    一、取url的bucketName 、endpoint 、objectName

    public static void main(String[] args) throws MalformedURLException {
            String fileName = "https://alanchen-bucket.oss-cn-shenzhen.aliyuncs.com/groupFile/a.jpg";
    
            URL address = new URL(fileName);
    
            //alanchen-bucket.oss-cn-shenzhen.aliyuncs.com
            String host = address.getHost();
    
            //alanchen-bucket
            String bucketName = host.split("\\.")[0];
    
            //oss-cn-shenzhen.aliyuncs.com
            String endpoint = host.replace(bucketName, "").replaceFirst(".","");
    
            //groupFile/a.jpg
            String objectName = address.getPath().replaceFirst("/", "");
        }
    

    二、OSS url授权给第三方使用(文件送审)

    2.1 方式一
    public String getOssUrl(String url) {
            try {
                URL address = new URL(url);
                String buckName = address.getHost().replace(ossConfig.getEndpoint(), "").replace(".","");
                String objectName = address.getPath().replaceFirst("/", "");
                String uri =OssUtils.getOSSUrlByObjectName(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret(),ossConfig.getRoleArn(), buckName, objectName);
                return uri;
            } catch (MalformedURLException malformedURLException) {
                log.warn(malformedURLException.getMessage());
            }
            return null;
        }
    
    2.2 方式二
    /**
         * https://help.aliyun.com/document_detail/32016.html
         * demo:https://alanchen-bucket.oss-cn-shenzhen.aliyuncs.com/groupFile/a.jpg
         * @param fileName
         * @return
         */
        @ApiOperation(value = "送审临时授权")
        @GetMapping("generatePresignedUrl")
        public Result<String> generatePresignedUrl(@RequestParam("fileName") String fileName) {
            OSS ossClient = null;
            try {
                URL address = new URL(fileName);
    
                //alanchen-bucket.oss-cn-shenzhen.aliyuncs.com
                String host = address.getHost();
    
                //alanchen-bucket
                String bucketName = host.split("\\.")[0];
    
                //oss-cn-shenzhen.aliyuncs.com
                String endpoint = host.replace(bucketName, "").replaceFirst(".","");
    
               //groupFile/a.jpg
                String objectName = address.getPath().replaceFirst("/", "");
    
                Map<String, String> tokenMap = OssUtils.generateToken(
                        ossConfig.getAccessKeyId(),
                        ossConfig.getAccessKeySecret(),
                        ossConfig.getRoleArn(),
                        ossConfig.getDurationSeconds(),
                        endpoint,
                        bucketName);
    
                String accessKeyId = tokenMap.get("AccessKeyId");
                String accessKeySecret = tokenMap.get("AccessKeySecret");
                String securityToken = tokenMap.get("SecurityToken");
                Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
    
                ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
                URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
    
                return Result.success(url.toString());
            } catch (Exception e) {
                log.error(e.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
            return Result.failed();
        }
    

    三、获取ossToken

        @ApiOperation(value = "获取ossToken")
        @ApiResponse(code = 200, message = "获取ossToken成功")
        @GetMapping("token")
        public Result getOssToken() {
            try {
                Map<String, String> token = OssUtils.generateToken(
                        ossConfig.getAccessKeyId(),
                        ossConfig.getAccessKeySecret(),
                        ossConfig.getRoleArn(),
                        ossConfig.getDurationSeconds(),
                        ossConfig.getEndpoint(),
                        ossConfig.getBucketName()
                );
    
                if (token != null) {
                    return Result.success(token);
                }
            } catch (ClientException ex) {
                throw new Exception(ex.getMessage());
            }
    
            return Result.failed(I18nUtils.message("oss.token"));
        }
    

    四、获取OSS元信息

        @ApiOperation(value = "获取OSS元信息")
        @ApiResponse(code = 200, message = "获取oss获取SimplifiedMeta成功")
        @GetMapping("simplifiedMeta")
        public Result getSimplifiedMeta(@RequestParam("objectName")String objectName) {
            try {
                SimplifiedObjectMeta meta = OssUtils.getOSSMetaByObjectName(
                        ossConfig.getEndpoint(),
                        ossConfig.getAccessKeyId(),
                        ossConfig.getAccessKeySecret(),
                        ossConfig.getBucketName(),
                        objectName);
    
                if (meta != null) {
                    return Result.success(meta);
                }
    
            } catch (Exception ex) {
                throw new Exception(ex.getMessage());
            }
            return Result.failed(I18nUtils.message("oss.simplified.meta"));
        }
    

    五、Service

    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.auth.sts.AssumeRoleRequest;
    import com.aliyuncs.auth.sts.AssumeRoleResponse;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.profile.DefaultProfile;
    import com.alanchen.oss.config.OssConfig;
    import com.alanchen.oss.dto.OssSecurityTokenDTO;
    import com.alanchen.oss.enums.BusinessTypeEnums;
    import com.alanchen.oss.service.OssServices;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Date;
    import java.time.LocalDateTime;
    import java.time.ZoneOffset;
    
    @Slf4j
    @Service
    public class OssServicesImpl implements OssServices {
        @Resource
        private OssConfig ossConfig;
        @Value("${spring.profiles.active}")
        private String active;
    
        @Override
        public AssumeRoleResponse getStsToken(String roleSessionName, String policy) {
            DefaultProfile profile = DefaultProfile.getProfile(ossConfig.getRegionId(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);
            AssumeRoleRequest request = new AssumeRoleRequest();
            request.setRoleArn(ossConfig.getRoleArn());
            if (null != policy) {
                request.setPolicy(policy);
            }
            request.setRoleSessionName(roleSessionName);
            request.setDurationSeconds(ossConfig.getDurationSeconds()); // 设置凭证有效时间
    
            try {
                return client.getAcsResponse(request);
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (com.aliyuncs.exceptions.ClientException e) {
                e.printStackTrace();
            }
            return null;
        }
    
    
        @Override
        public OssSecurityTokenDTO getSecurityToken(BusinessTypeEnums businessTypeEnums, String busiId) {
            String policy = getPolicy(businessTypeEnums, busiId);
            AssumeRoleResponse response = getStsToken(businessTypeEnums.getCode() + "-" + busiId, policy);
    
            return OssSecurityTokenDTO.builder()
                    .accessKeyId(response.getCredentials().getAccessKeyId())
                    .accessKeySecret(response.getCredentials().getAccessKeySecret())
                    .endpoint(ossConfig.getEndpoint())
                    .bucketName(businessTypeEnums.getBucketName())
                    .expiration(ossConfig.getDurationSeconds())
                    .securityToken(response.getCredentials().getSecurityToken())
                    .build();
        }
    
        @Override
        public OssSecurityTokenDTO getSecurityToken(String bucketName) {
            AssumeRoleResponse response = getStsToken(bucketName, null);
    
            return OssSecurityTokenDTO.builder()
                    .accessKeyId(response.getCredentials().getAccessKeyId())
                    .accessKeySecret(response.getCredentials().getAccessKeySecret())
                    .endpoint(ossConfig.getEndpoint())
                    .bucketName(bucketName)
                    .expiration(ossConfig.getDurationSeconds())
                    .securityToken(response.getCredentials().getSecurityToken())
                    .build();
        }
    
        @Override
        public OssSecurityTokenDTO getMemberSecurityToken(Long memberId) {
            String policy = getMemberPolicy(memberId);
            AssumeRoleResponse response = getStsToken("ALL-" + memberId, policy);
    
            return OssSecurityTokenDTO.builder()
                    .accessKeyId(response.getCredentials().getAccessKeyId())
                    .accessKeySecret(response.getCredentials().getAccessKeySecret())
                    .endpoint(ossConfig.getEndpoint())
                    .expiration(ossConfig.getDurationSeconds())
                    .securityToken(response.getCredentials().getSecurityToken())
                    .gTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")))
                    .build();
        }
    
        @Override
        public OssSecurityTokenDTO getPublicSecurityToken() {
            String policy = getPublicPolicy();
            AssumeRoleResponse response = getStsToken("PUBLIC", policy);
    
            return OssSecurityTokenDTO.builder()
                    .accessKeyId(response.getCredentials().getAccessKeyId())
                    .accessKeySecret(response.getCredentials().getAccessKeySecret())
                    .endpoint(ossConfig.getEndpoint())
                    .expiration(ossConfig.getDurationSeconds())
                    .securityToken(response.getCredentials().getSecurityToken())
                    .build();
        }
    
        @Override
        public String getUrl(String url) {
            try {
                URL address = new URL(url);
                String buckName = address.getHost().replace(ossConfig.getEndpoint(), "").replace(".", "");
                String objectName = address.getPath().replaceFirst("/", "");
    
                OssSecurityTokenDTO token = getSecurityToken(buckName);
                OSS ossClient = new OSSClientBuilder().build(token.getEndpoint(), token.getAccessKeyId(), token.getAccessKeySecret(), token.getSecurityToken());
    
    // 设置签名URL过期时间为3600秒(1小时)。
                Date expiration = new Date(new Date().getTime() + 3600 * 1000);
    // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
                URL newUrl = ossClient.generatePresignedUrl(buckName, objectName, expiration);
                return newUrl.toString();
            }catch (MalformedURLException malformedURLException) {
                log.warn(malformedURLException.getMessage());
            }
            return null;
    
        }
    
        private String getMemberPolicy(Long memberId) {
            String policy = "{\n" +
                    "    \"Version\": \"1\", \n" +
                    "    \"Statement\": [\n" +
                    "        {\n" +
                    "            \"Action\": [\n" +
                    "                \"oss:*\"\n" +
                    "            ], \n" +
                    "            \"Resource\": [\n" +
                    "                \"acs:oss:*:*:alanchen-" + active + "-op/*\", \n" +
                    "                \"acs:oss:*:*:alanchen-" + active + "-public/*\", \n" +
                    "                \"acs:oss:*:*:alanchen-" + active + "-private/content/" + memberId + "/*\" \n" +
                    "            ], \n" +
                    "            \"Effect\": \"Allow\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            return policy;
        }
    
        private String getPublicPolicy() {
            String policy = "{\n" +
                    "    \"Version\": \"1\", \n" +
                    "    \"Statement\": [\n" +
                    "        {\n" +
                    "            \"Action\": [\n" +
                    "                \"oss:*\"\n" +
                    "            ], \n" +
                    "            \"Resource\": [\n" +
                    "                \"acs:oss:*:*:alanchen-prod-op/*\" \n" +
                    "                \"acs:oss:*:*:alanchen-prod-pubic/*\" \n" +
                    "            ], \n" +
                    "            \"Effect\": \"Allow\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            return policy;
        }
    
        private String getPolicy(BusinessTypeEnums businessTypeEnums, String busiId) {
    
            String policy = "{\n" +
                    "    \"Version\": \"1\", \n" +
                    "    \"Statement\": [\n" +
                    "        {\n" +
                    "            \"Action\": [\n" +
                    "                \"oss:*\"\n" +
                    "            ], \n" +
                    "            \"Resource\": [\n" +
                    "                \"acs:oss:*:*:" + businessTypeEnums.getBucketName() + "/" + businessTypeEnums.getCode() + "/" + busiId + "/*\" \n" +
                    "            ], \n" +
                    "            \"Effect\": \"Allow\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            return policy;
        }
    
    }
    

    相关文章

      网友评论

          本文标题:阿里云OSS代码集

          本文链接:https://www.haomeiwen.com/subject/oxoumrtx.html