阅读988 返回首页    go iPhone_iPad_Mac_apple


请求安全令牌-Java示例代码__上传视频文件_开发人员指南_视频点播-阿里云

返回:简介 >>

上传视频文件-请求安全令牌-Java示例代码

  1. pom.xml中引用STS的SDK

    1. <dependencies>
    2. <dependency>
    3. <groupId>com.aliyun</groupId>
    4. <artifactId>aliyun-java-sdk-sts</artifactId>
    5. <version>2.1.6</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>com.aliyun</groupId>
    9. <artifactId>aliyun-java-sdk-core</artifactId>
    10. <version>2.2.0</version>
    11. </dependency>
    12. </dependencies>
  2. 代码

    STS需要一个角色的参数:roleArn。登录阿里云控制台后,可以点击这里,然后点击具体角色名后,在基本信息中有一个参数:Arn,例如1351140512345678:role/teststs

    • main函数
    1. public static void main(String[] args) throws Exception {
    2. IClientProfile profile = DefaultProfile.getProfile(
    3. "cn-hangzhou",
    4. <accessKeyId>,
    5. <accessKeySecret>);
    6. DefaultAcsClient client = new DefaultAcsClient(profile);
    7. AssumeRoleResponse response = assumeRole(client, <roleArn>);
    8. AssumeRoleResponse.Credentials credentials = response.getCredentials();
    9. System.out.println(credentials.getAccessKeyId() + "n" +
    10. credentials.getAccessKeySecret() + "n" +
    11. credentials.getSecurityToken() + "n" +
    12. credentials.getExpiration());
    13. }
    • 生成临时AK和Token的函数
    1. private static AssumeRoleResponse assumeRole(
    2. DefaultAcsClient client,
    3. String roleArn)
    4. throws ClientException {
    5. final AssumeRoleRequest request = new AssumeRoleRequest();
    6. request.setVersion("2015-04-01");
    7. request.setMethod(MethodType.POST);
    8. request.setProtocol(ProtocolType.HTTPS);
    9. request.setDurationSeconds(900L);
    10. request.setRoleArn(roleArn);
    11. request.setRoleSessionName("test-token");
    12. return client.getAcsResponse(request);
    13. }
  3. Token有效期

    示例代码中生成的Token有效时间为900秒,可以根据实际需求调整(最小900秒,最大3600秒)。

    在有效期内,不需要反复生成新的Token,可以复用已经生成的Token,如何判断什么时候需要重新生成呢?

    1. private static boolean isTimeExpire(String expiration) {
    2. Date nowDate = new Date();
    3. Date expireDate = javax.xml.bind.DatatypeConverter.parseDateTime(expiration).getTime();
    4. if (expireDate.getTime() <= nowDate.getTime()) {
    5. return true;
    6. } else {
    7. return false;
    8. }
    9. }

返回:简介 >>

最后更新:2016-10-13 11:51:16

  上一篇:go 设置CORS__上传视频文件_开发人员指南_视频点播-阿里云
  下一篇:go 队列方式接收通知__接收消息通知_开发人员指南_视频点播-阿里云