全部产品
媒体转码

请求安全令牌-Java示例代码

更新时间:2017-06-07 13:26:11   分享:   

返回:简介 >>

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

  1. pom.xml中引用STS的SDK

    1. <repositories>
    2. <repository>
    3. <id>sonatype-nexus-staging</id>
    4. <name>Sonatype Nexus Staging</name>
    5. <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    6. <releases>
    7. <enabled>true</enabled>
    8. </releases>
    9. <snapshots>
    10. <enabled>true</enabled>
    11. </snapshots>
    12. </repository>
    13. </repositories>
    14. <dependencies>
    15. <dependency>
    16. <groupId>com.aliyun</groupId>
    17. <artifactId>aliyun-java-sdk-sts</artifactId>
    18. <version>2.1.6</version>
    19. </dependency>
    20. <dependency>
    21. <groupId>com.aliyun</groupId>
    22. <artifactId>aliyun-java-sdk-core</artifactId>
    23. <version>2.2.0</version>
    24. </dependency>
    25. </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. }

返回:简介 >>

本文导读目录
本文导读目录
以上内容是否对您有帮助?