Browse Source

完成对阿里云oss资源的动态加密,未加密的不能访问

yaobo 7 years ago
parent
commit
49096f4d17
1 changed files with 19 additions and 1 deletions
  1. 19 1
      src/main/java/cn/efunbox/audio/plugin/AliStsService.java

+ 19 - 1
src/main/java/cn/efunbox/audio/plugin/AliStsService.java

@@ -1,5 +1,6 @@
 package cn.efunbox.audio.plugin;
 
+import com.aliyun.oss.OSSClient;
 import com.aliyuncs.DefaultAcsClient;
 import com.aliyuncs.exceptions.ClientException;
 import com.aliyuncs.http.MethodType;
@@ -9,6 +10,9 @@ import com.aliyuncs.profile.IClientProfile;
 import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
 import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
 
+import java.net.URL;
+import java.util.Date;
+
 /**
  * Created by yao on 17-10-10.
  */
@@ -57,7 +61,7 @@ public class AliStsService {
         String policy = "{\n" +
                 "  \"Statement\": [\n" +
                 "    {\n" +
-                "      \"Action\": \"sts:AssumeRole\",\n" +
+                "      \"Action\": \"oss:*\",\n" +
                 "      \"Effect\": \"Allow\",\n" +
                 "      \"Resource\": \"*\"\n" +
                 "    }\n" +
@@ -69,10 +73,24 @@ public class AliStsService {
         try {
             final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
                     roleArn, roleSessionName, policy, protocolType);
+
             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());
+
+            String accessKeyIdTemp = response.getCredentials().getAccessKeyId();
+            String accessKeySecretTemp = response.getCredentials().getAccessKeySecret();
+            String securityTokenTemp = response.getCredentials().getSecurityToken();
+            String endpoint = "oss-cn-beijing.aliyuncs.com";
+            OSSClient client = new OSSClient(endpoint, accessKeyIdTemp, accessKeySecretTemp, securityTokenTemp);
+            String bucketName = "efunaudio";
+            String key = "audio/001/00103035/00103035018.mp3";
+            // 设置URL过期时间为1小时
+            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
+            // 生成URL
+            URL url = client.generatePresignedUrl(bucketName, key, expiration);
+            System.out.println(url.toString());
         } catch (ClientException e) {
             System.out.println("Failed to get a token.");
             System.out.println("Error code: " + e.getErrCode());