All Products
Search
Document Center

ApsaraVideo VOD:Use STS to upload videos

Last Updated:Dec 11, 2023

You can use Security Token Service (STS) to generate temporary access credentials and use the credentials to upload videos to ApsaraVideo VOD. This prevents security risks caused by leaks of RAM user passwords. This topic describes how to use STS to authorize temporary access to ApsaraVideo VOD.

Step 1: Create a RAM user

Note
  • In Step 4, we recommend that you set Logon Name to vod. This topic uses vod as an example.

  • In Step 5, we recommend that you set Access Mode to OpenAPI Access.

  1. Log on to the RAM console by using an Alibaba Cloud account or a RAM user that has administrative rights.

  2. In the left-side navigation pane, choose Identities > Users.

  3. On the Users page, click Create User.

  4. In the User Account Information section of the Create User page, configure the following parameters:

    • Logon Name: The logon name can be up to 64 characters in length, and can contain letters, digits, periods (.), hyphens (-), and underscores (_).

    • Display Name: The display name can be up to 128 characters in length.

    • Tag: Click the edit icon and enter a tag key and a tag value. You can add one or more tags to the RAM user. This way, you can manage the RAM user based on the tags.

    Note

    You can click Add User to create multiple RAM users at a time.

  5. In the Access Mode section, select an access mode and configure the required parameters.

    To ensure the security of your Alibaba Cloud account, we recommend that you select only one access mode for the RAM user. This way, the RAM user for an individual is separated from the RAM user for a program.

    • Console Access

      If the RAM user represents an individual, we recommend that you select Console Access for the RAM user. This way, the RAM user can use a username and password to access Alibaba Cloud. If you select Console Access, you must configure the following parameters:

      • Set Console Password: You can select Automatically Regenerate Default Password or Reset Custom Password. If you select Reset Custom Password, you must specify a password. The password must meet the complexity requirements. For more information, see Configure a password policy for RAM users.

      • Password Reset: specifies whether the RAM user is required to reset the password upon the next logon.

      • Enable MAF: specifies whether to enable multi-factor authentication (MFA) for the RAM user. After you enable MFA, you must bind an MFA device to the RAM user or allow the RAM user to bind an MFA device. For more information, see Bind an MFA device to a RAM user.

    • OpenAPI Access

      If the RAM user represents a program, we recommend that you select OpenAPI Access for the RAM user. This way, the RAM user can use an AccessKey pair to access Alibaba Cloud. If you select OpenAPI Access, the system automatically generates an AccessKey ID and AccessKey secret for the RAM user. For more information, see Obtain an AccessKey pair.

      Important

      An AccessKey secret for a RAM user is displayed only after you click Create AccessKey. You cannot query the AccessKey secret in subsequent operations. Therefore, you must back up your AccessKey secret.

  6. Click OK.

  7. Complete security verification as prompted.

Step 2: Grant the RAM user permissions to call the AssumeRole operation of STS

  1. Log on to the RAM console. In the left-side navigation pane, choose Identities > Users. On the Users page, find the RAM user named vod and click Add Permissions in the Actions column.

  2. In the Add Permissions panel, grant permissions to the RAM user.

    Note

    Attach the AliyunSTSAssumeRoleAccess policy to the vod user. This allows the user to call the AssumeRole operation. You can enter AliyunSTSAssumeRoleAccess in the search box to search for the system policy.

    选择策略

    1. Select the authorization scope.

      • Alibaba Cloud Account: The authorization takes effect on the current Alibaba Cloud account.

      • Specific Resource Group: The authorization takes effect on a specific resource group.

        Note

        If you select Specific Resource Group for Authorized Scope, make sure that the required cloud service supports resource groups. For more information, see Services that work with Resource Group.

    2. Specify the principal.

      The principal is the RAM user to which you want to grant permissions.

    3. Select policies.

      RAM supports the following types of policies: system policies and custom policies. You can choose policies based on your business requirements.

      Note

      You can attach a maximum of five policies to a RAM user at a time. If you want to attach more than five policies to a RAM user, perform the operation multiple times.

  3. Click OK.

  4. Click Complete.

Step 3: Create a RAM role

Note

We recommend that you set Role Name that is mentioned in Step 5 to vodrole. In this topic, vodrole is used as an example.

  1. Log on to the RAM console by using an Alibaba Cloud account or a RAM user that has administrative rights.

  2. In the left-side navigation pane, choose Identities > Roles.

  3. On the Roles page, click Create Role.

  4. In the Create Role panel, select Alibaba Cloud Account for the Select Trusted Entity parameter and click Next.

  5. Configure parameters for the RAM role.

    1. Specify RAM Role Name.

    2. Specify Note.

    3. Select Current Alibaba Cloud Account or Other Alibaba Cloud Account.

      • Current Alibaba Cloud Account: If you want a RAM user that belongs to your Alibaba Cloud account to assume the RAM role, select Current Alibaba Cloud Account.

      • Other Alibaba Cloud Account: If you want a RAM user that belongs to a different Alibaba Cloud account to assume the RAM role, select Other Alibaba Cloud Account and enter the ID of the Alibaba Cloud account. This option is provided to grant permissions on resources that belong to different Alibaba Cloud accounts. For more information, see Use a RAM role to grant permissions across Alibaba Cloud accounts.

      Important
  6. Click OK.

  7. Click Close.

Step 4: Grant the RAM role permissions to access ApsaraVideo VOD

  1. Log on to the RAM console. In the left-side navigation pane, choose Identities > Roles. On the Roles page, find the RAM role named vodrole and click Add Permissions in the Actions column.

  2. In the Add Permissions panel, grant permissions to the RAM role.

    Note
    • To improve security, we recommend that you grant only the minimum required permissions to the RAM role.

    • If you want the vodrole role to access and manage resources in ApsaraVideo VOD, we recommend that you attach the AliyunVODFullAccess policy to the vodrole role. You can enter AliyunVODFullAccess in the search box to find the policy. For more information about the system policies and permissions of ApsaraVideo VOD, see System policies.

    授权

    1. Set the authorization scope.

      • Alibaba Cloud Account: The authorization takes effect on the current Alibaba Cloud account.

      • Specific Resource Group: The authorization takes effect on a specific resource group.

        Note

        If you select Specific Resource Group for Authorized Scope, make sure that the required cloud service supports resource groups. For more information, see Services that work with Resource Group.

    2. Specify the principal.

      The principal is the RAM role to which permissions are granted. By default, the current RAM role is specified. You can also specify a different RAM role.

    3. Select policies.

      Note

      You can attach a maximum of five policies to a RAM role at a time. If you need to attach more than five policies to a RAM role, perform the operation multiple times.

    After you grant permissions to the role, a successful authorization record is generated.授权成功

Step 5: Use STS to access ApsaraVideo VOD

Note

This section describes how to call an API operation to assume a RAM role and use an STS token to access ApsaraVideo VOD.

Use the RAM user that you created to call the AssumeRole operation to obtain the STS token. Then, use the STS token to access ApsaraVideo VOD.

The following content provides the Java sample code for obtaining the STS token. For more information about how to integrate the STS SDK and sample code in other languages, see STS SDK overview.

Sample code in Java

package pop;

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;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;

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

    public static void main(String[] args) {
        // Obtain the AccessKey pair (AccessKey ID and AccessKey secret) that is generated in Step 1 from the environment variables. 
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Request parameters for the AssumeRole operation include RoleArn, RoleSessionName, Policy, and DurationSeconds.
        // Obtain RoleArn in the RAM console in Step 3.
        String roleArn = "<role-arn>";
        // RoleSessionName specifies the session name of the role. You can specify a custom value for this parameter.
        String roleSessionName = "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, see the STS endpoints in different regions. 
             */
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // Use the profile to construct a client.
            DefaultAcsClient client = new DefaultAcsClient(profile);
            // Create an AssumeRole request and configure 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;
        }
    }

    static void createUploadVideo(String accessKeyId, String accessKeySecret, String token) {
        // Specify the region of ApsaraVideo VOD. For example, if the service region is Shanghai, set regionId to cn-shanghai.
        String regionId = "cn-shanghai";
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setSecurityToken(token);
        request.setTitle("t5");
        request.setFileName("D:\\TestVideo\\t4.mp4");
        request.setFileSize(10240L);

        try {
            CreateUploadVideoResponse response = client.getAcsResponse(request);
            System.out.println("CreateUploadVideoRequest, " + request.getUrl());
            System.out.println("CreateUploadVideoRequest, requestId:" + response.getRequestId());
            System.out.println("UploadAddress, " + response.getUploadAddress());
            System.out.println("UploadAuth, " + response.getUploadAuth());
            System.out.println("VideoId, " + response.getVideoId());
        } catch (ClientException e) {
            System.out.println("action, error:" + e);
            e.printStackTrace();
        }
    }
}