This topic describes how to obtain a Security Token Service (STS) token. This prepares you for the initialization of an upload instance when you use a client upload SDK to upload files.

Background information

When media files are uploaded from clients, the files are directly uploaded to Object Storage Service (OSS) buckets allocated by ApsaraVideo VOD without the need to pass through servers. Therefore, the clients must be authenticated. You must deploy the authorization service on the AppServer to obtain an upload URL and credential. Client upload SDKs support the following authorization methods:
  • Use an upload URL and credential.
  • Use an STS token.

STS provides a universal service for authenticating the access to Alibaba Cloud services. A client SDK for uploading media files by using STS tokens encapsulates all the upload logic. You need to only focus on the configurations for obtaining the STS token, updating the STS token when it expires, and setting the callback for upload completion. For more information about whether to upload media files by using upload URLs and credentials or STS tokens, see Comparison between credentials and STS. For more information about how to upload media files by using upload URLs and credentials, see Obtain upload URLs and credentials.

Process

For more information about how to upload media files by using STS tokens, see Upload processes.

Obtain an STS token

To skip the signature process, we recommend that you integrate STS SDK and call the AssumeRole operation to obtain an STS token. Before you integrate STS SDK, you must create a RAM user and assign a role that has the permissions to access ApsaraVideo VOD to the user.

  1. Create a RAM user. For more information, see Create a role and grant temporary access permissions to the role by using STS.
  2. Optional. Attach custom authorization policies to the RAM user. For more information, see Use custom policies.
  3. Integrate STS SDK and call the AssumeRole operation to obtain an STS token. The substeps of this step vary based on the programming language of the server.
    Programming language of the server Operation guide
    Java STS SDK for Java
    Note The following section provides sample code in Java.
    Python STS SDK for Python
    PHP STS SDK for PHP
    .NET STS SDK for .NET
    Node.js STS SDK for Node.js
    Go STS SDK for Go

Sample code in Java

Sample Java code on how to obtain an STS token

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;


/**
 * @author jack
 * @date 2020/5/25
 */
public class TestStsService {

    public static void main(String[] args) {
        // Only RAM users can call the AssumeRole operation.
        // AccessKey pairs of Alibaba Cloud accounts cannot be used to initiate AssumeRole requests.
        // Create a RAM user in the Resource Access Management (RAM) console and create an AccessKey pair for the RAM user.
        String accessKeyId = "LTAI5tKtf6vKccbinQu****";
        String accessKeySecret = "D47l1yBPgjdqe3JzVASSF9yrje****";
        // Request parameters for the AssumeRole operation include RoleArn, RoleSessionName, Policy, and DurationSeconds.
        // RoleArn: You can obtain the value of this parameter in the RAM console.
        String roleArn = "acs:ram::1748098430911242:role/vodrole";
        // RoleSessionName: the session name of the role. You can set this parameter based on your needs.
        String roleSessionName = "session-name";// Specify a session name.
        // Specify a policy.
        String policy = "{\n" +
                "  \"Version\": \"1\",\n" +
                "  \"Statement\": [\n" +
                "    {\n" +
                "      \"Action\": \"vod:*\",\n" +
                "      \"Resource\": \"*\",\n" +
                "      \"Effect\": \"Allow\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        try {
            AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy);
            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());

            createUploadVideo(response.getCredentials().getAccessKeyId(), response.getCredentials().getAccessKeySecret(), response.getCredentials().getSecurityToken());
        } 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());
        }
    }

    static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn, String roleSessionName, String policy) throws ClientException {
        try {
            // Construct a default profile. Leave the parameters empty. The regionId parameter is not required.
            /*
            Note: If you set SysEndpoint to sts.aliyuncs.com, the regionId parameter is optional. Otherwise, you must set the regionId parameter to the region in which you use STS. Example: cn-shanghai.
            For more information about the STS endpoints in different regions, see Endpoints. 
             */
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // Use the profile to construct a client.
            DefaultAcsClient client = new DefaultAcsClient(profile);
            // Create an AssumeRole request and set the request parameters.
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setSysEndpoint("sts.aliyuncs.com");
            request.setSysMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy);
            // Initiate the request and obtain the response.
            final AssumeRoleResponse response = client.getAcsResponse(request);
            return response;
        } catch (ClientException e) {
            throw e;
        }
    }
                

Parameters

Parameter Description
RoleArn The Alibaba Cloud Resource Name (ARN) of the role to be assumed. After you create a role for the RAM user, you can perform the following steps to view the ARN of the role: Log on to the RAM console and choose Identities > Roles. Click the required role and view the ARN in the Basic Information section.
RoleSessionName The custom name of the role session. Set this parameter based on your business requirements. In most cases, this parameter is set to the identity of the user who calls the operation, for example, the username. In ActionTrail logs, you can distinguish the users who assume the same RAM role to perform operations based on the value of the RoleSessionName parameter. This way, you can perform user-specific auditing. The value must be 2 to 64 characters in length and can contain letters, digits, periods (.), at signs (@), hyphens (-), and underscores (_).
Policy The policy that specifies the permissions added when a role is assumed.
Note
  • The policy is used to control the permissions of the temporary access credential after the user assumes a role. The final permissions obtained by the temporary access credentials are an intersection of the permissions of the role and the permissions specified by the policy.
  • The Policy parameter is passed in to improve flexibility. For example, you can set this parameter to specify that only the CreateUploadVideo operation can be called.
DurationSeconds The validity period of the temporary access credential. Valid values: 900 to 3600. Unit: seconds.
accessKeyId and accessKeySecret The AccessKey ID and AccessKey secret of the RAM user that assumes the role.

Use STS tokens to upload media files

Each media file requires an STS token. Therefore, you must obtain the STS token from the AppServer and specify the STS token for the upload instance in the onUploadStarted callback. The specific settings vary based on different clients.

Client User guide
Web Upload SDK for JavaScript
Android Upload a file
iOS Upload a file
WeChat mini program Upload SDK for WeChat mini programs