All Products
Search
Document Center

ApsaraVideo VOD:Use STS to upload videos

Last Updated:Jul 05, 2024

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 who 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 Grant Permission in the Actions column.

  2. In the Grant Permission 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. Configure the Resource Scope parameter.

    2. Configure the Principal parameter.

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

    3. Configure the Policy parameter.

      A policy contains a set of permissions. Policies can be classified into system policies and custom policies. You can select multiple policies at a time.

      • System policies: policies that are created by Alibaba Cloud. You can use but cannot modify these policies. Version updates of the policies are maintained by Alibaba Cloud. For more information, see Services that work with RAM.

        Note

        The system automatically identifies high-risk system policies, such as AdministratorAccess and AliyunRAMFullAccess. We recommend that you do not grant unnecessary permissions by attaching high-risk policies.

      • Custom policies: You can manage and update custom policies based on your business requirements. You can create, update, and delete custom policies. For more information, see Create a custom policy.

    4. Click Grant permissions.

  3. Click Close.

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 as a RAM user who has administrative rights.

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

  3. On the Roles page, click Create Role.

  4. On the Create Role page, select Alibaba Cloud Account in the Select Role Type section 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 in the Select Trusted Alibaba Cloud Account section.

      • 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.

        You can view the ID of your Alibaba Cloud account on the Security Settings page.

      Important

      If you want a specific RAM user instead of all RAM users that belong to your Alibaba Cloud account to assume the RAM role, you can use one of the following methods:

  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 Grant Permission in the Actions column.

  2. In the Grant Permission 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. Configure the Resource Scope parameter.

    2. Configure the Principal parameter.

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

    3. Configure the Policy parameter.

      A policy contains a set of permissions. Policies can be classified into system policies and custom policies. You can select multiple policies at a time.

      • System policies: policies that are created by Alibaba Cloud. You can use but cannot modify these policies. Version updates of the policies are maintained by Alibaba Cloud. For more information, see Services that work with RAM.

        Note

        The system automatically identifies high-risk system policies, such as AdministratorAccess and AliyunRAMFullAccess. We recommend that you do not grant unnecessary permissions by attaching high-risk policies.

      • Custom policies: You can manage and update custom policies based on your business requirements. You can create, update, and delete custom policies. For more information, see Create a custom policy.

    4. Click Grant permissions.

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

  3. Click Close.

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();
        }
    }
}