Request a security token

更新时间:
复制 MD 格式

Encrypted videos in MPS must be played using a media ID, which requires a Security Token Service (STS) token for access control. The STS token grants temporary, scoped access without exposing your primary account credentials. This topic describes how to request an STS token using the RAM STS SDK (Java).

Prerequisites

Before you begin, ensure that you have:

  • Installed the RAM STS SDK. For setup instructions, see Java example. For other languages, see STS SDK overview.

  • Retrieved the roleArn of the RAM role that the STS token will assume. To get the ARN, log on to the RAM console, choose Identities > Roles, click the target role, and copy the value in the ARN field.

Request an STS token

An STS token is a short-lived credential. When your application calls assumeRole, it receives a temporary AccessKey pair and a security token that expire after a configured duration. This approach avoids embedding long-term credentials in client-side code.

  1. Add the STS SDK dependency to your pom.xml file.

    <repositories>
         <repository>
             <id>sonatype-nexus-staging</id>
             <name>Sonatype Nexus Staging</name>
             <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
             <releases>
                 <enabled>true</enabled>
             </releases>
             <snapshots>
                 <enabled>true</enabled>
             </snapshots>
         </repository>
     </repositories>
    <dependencies>
     <dependency>
       <groupId>com.aliyun</groupId>
       <artifactId>aliyun-java-sdk-sts</artifactId>
       <version>2.1.6</version>
     </dependency>
     <dependency>
       <groupId>com.aliyun</groupId>
       <artifactId>aliyun-java-sdk-core</artifactId>
       <version>2.2.0</version>
     </dependency>
    </dependencies>
    Note

    Visit the Maven repository to get the latest version of aliyun-java-sdk-core.

  2. Call assumeRole to generate a temporary AccessKey pair and security token.

    The key request parameters are:

    Parameter

    Description

    Example value

    roleArn

    Alibaba Cloud Resource Name (ARN) of the RAM role to assume

    acs:ram::174*****11242:role/sts-role

    DurationSeconds

    Token validity period in seconds. Valid range: 900–3,600

    900

    RoleSessionName

    A label for this session, used in audit logs

    test-token

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.http.MethodType;
    import com.aliyuncs.http.ProtocolType;
    import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
    import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
    /**
     * You can call this operation only as a RAM user.
     */
    public class STSTokenDemo {
        public static void main(String[] args) throws Exception {
            // Initialize the client.
            DefaultAcsClient client = InitClient.initMpsClient();
            // The roleArn must be obtained from the RAM console.
            String roleArn = "acs:ram::174*********11242:role/sts-role";
            try {
                AssumeRoleResponse response = assumeRole(client, roleArn);
                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 to get a token.");
                System.out.println("Error code: " + e.getErrCode());
                System.out.println("Error message: " + e.getErrMsg());
            }
        }
        /** Generates a temporary AccessKey pair and a security token. */
        private static AssumeRoleResponse assumeRole(
                DefaultAcsClient client,
                String roleArn)
                throws ClientException {
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setVersion("2015-04-01");
            request.setMethod(MethodType.POST);
            request.setProtocol(ProtocolType.HTTPS);
            request.setDurationSeconds(900L);
            request.setRoleArn(roleArn);
            request.setRoleSessionName("test-token");
            return client.getAcsResponse(request);
        }
    }
  3. Set the token validity period.

    Set DurationSeconds to a value between 900 and 3,600 seconds. Choose a period long enough to cover the expected playback duration. If the token expires during playback, the video stops and the user must obtain a new token. For long videos or sessions where users may pause and resume, use a longer validity period.

    You can reuse a token until it expires. Use the following helper to check token expiry before making a new request:

    private static boolean isTimeExpire(String expiration) {
         Date nowDate = new Date();
         Date expireDate = javax.xml.bind.DatatypeConverter.parseDateTime(expiration).getTime();
         if (expireDate.getTime() <= nowDate.getTime()) {
             return true;
         } else {
             return false;
         }
    }

Related topics