Temporary access permission to OSS can be granted by using Alibaba Cloud Security Token Service (STS). You can use STS to grant a third-party application or a RAM user (whose user ID is managed by you) an access credential with a customized validity period and permissions.

Scenarios

Users managed by your local identity system are referred to as federated users, such as the users of your applications, local accounts owned by your enterprise, or users of third-party applications. In addition, federated users can also be users that are created by you and who have access to your applications and resources in Alibaba Cloud. Federated users may need to access your OSS resources directly.

For these users, you can use STS to manage the temporary access credentials for their Alibaba Cloud accounts or RAM users. You can create temporary access credentials for federated users to grant OSS access permissions to them without providing your long-term keys (such as logon passwords and AccessKey pairs) of your Alibaba Cloud accounts or RAM users to the federated users. You can customize the access permissions and validity period of the credential. The temporary access credential automatically becomes invalid when it expires.

Temporary access credentials generated by STS include security tokens (SecurityToken) and temporary AccessKey pairs composed of AccessKey ID and AccessKey secret. You can use a temporary AccessKey pair to access OSS in the same way as you would use an AccessKey pair of an Alibaba Cloud account or a RAM user to send a request. Each request sent to OSS must carry a security token.

Implementation

A mobile app is used as an example. Assume that you are a mobile app developer and plan to use Alibaba Cloud OSS to store end user data for your app. You must keep the data of each app user isolated to prevent an app user from obtaining data of other app users. You can use STS to authorize users so that they can directly access your OSS resources.

The following figure shows how to use STS to grant OSS access to users.

  1. Log on as the app user. An app user is an end user of the app and is irrelevant to an Alibaba Cloud account. An app user can log on to the app server. The app server must be capable of defining the minimum access permissions for each valid app user.
  2. The App server requests a security token from STS. Before calling STS, the app server must determine the minimum access permissions for each app user (described in the policy syntax) and the expiration time of the authorization. Then, the app server uses AssumeRole to obtain a security token which indicates a role.
  3. STS returns a temporary access credential to the app server. The credential includes a security token (SecurityToken), a temporary AccessKey pair (AccessKey ID and AccessKey secret), and the expiration time.
  4. The app server returns the temporary access credential to the app client. The app client can cache the credential. After the credential expires, the app client must apply for a new temporary access credential from the app server. For example, if the temporary access credential is valid for one hour, the app client can send a request to the app server to update the credential every 30 minutes.
  5. The app client uses the cached temporary access credential to initiate a request to call OSS API operations. After receiving the request, OSS uses STS to verify the access credential in the request and responds the request.

Procedure

By combining OSS SDKs and STS SDKs, you can access OSS with a temporary access credential provided by STS. Assume that a bucket named ram-test is used to store user data. STS is used to grant permissions to a RAM user so that the user can access OSS buckets.

  1. Create a RAM user.
    1. Log on to the RAM console by using an Alibaba Cloud account.
    2. In the left-side navigation pane, click Users under Identities.
    3. Click Create User.
      Note To create multiple RAM users at a time, click Add User.
    4. Specify the Logon Name and Display Name parameters.
    5. Under Access Mode, select Programmatic Access.
    6. Click OK. Click Copy in the Actions column that corresponds to the created RAM user and save the AccessKey pair (AccessKey ID and AccessKey secret).
    7. Select the created RAM user. Click Add Permissions.
    8. In the Add Permissions dialog box that appears, add the AliyunSTSAssumeRoleAccess policy to created RAM user.
      Note Do not grant other permissions to the RAM user because it automatically obtains all permissions of a role when it assumes the role.
    9. Click OK.
  2. Create a permission policy.
    1. Log on to the RAM console by using an Alibaba Cloud account.
    2. In the left-side navigation pane, click Policies under Permissions.
    3. On the page that appears, click Create Policy.
    4. On the Create Custom Policy page, specify the Policy Name and Note parameters.
    5. Select Visualized or Script for Configuration Mode.
      For example, if you select Script and want to grant read-only permissions, such as ListObjects and GetObject, to ram-test, add the following script in the Policy Document section.
      {
          "Version": "1",
          "Statement": [
           {
                 "Effect": "Allow",
                 "Action": [
                   "oss:ListObjects",
                   "oss:GetObject"
                 ],
                 "Resource": [
                   "acs:oss:*:*:ram-test",
                   "acs:oss:*:*:ram-test/*"
                 ]
           }
          ]
      }
      Note For more information about how to configure fine-grained permission policies, see Implement access control based on RAM policies.
  3. Create a role and record the role ARN.
    1. Log on to the RAM console by using an Alibaba Cloud account.
    2. In the left-side navigation pane, click RAM Roles.
    3. Click Create RAM Role, select Alibaba Cloud Account, and then click Next.
    4. In the Create RAM Role dialog box that appears, enter the RAM Role Name and Note. In this example, the RAM role name is RamOssTest.
    5. under Select Trusted Alibaba Cloud Account, select Current Alibaba Cloud Account.
    6. Click OK. Then, click Add Permissions to RAM role.
    7. In the Add Permissions dialog box, select Custom Policy and add the policy that you created in step 2.
      After the policy is added, the following page appears.
    8. Record the ARN of the role.
      Note ARN indicates the ID of the role that the RAM user assumes.
  4. Obtain an STS AccessKey pair and a security token.

    You can call the AssumeRole operation or use STS SDKs in various languages to obtain the temporary access credential.

    The following code provides an example on how to use the Java SDK to obtain a temporary access credential:
    package com.aliyun.sts.sample;
    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;
    public class StsServiceSample {
        public static void main(String[] args) {        
            String endpoint = "<sts-endpoint>";
            String AccessKeyId = "<access-key-id>";
            String accessKeySecret = "<access-key-secret>";
            String roleArn = "<role-arn>";
            String roleSessionName = "<session-name>";
            String policy = "{\n" +
                    "    \"Version\": \"1\", \n" +
                    "    \"Statement\": [\n" +
                    "        {\n" +
                    "            \"Action\": [\n" +
                    "                \"oss:*\"\n" +
                    "            ], \n" +
                    "            \"Resource\": [\n" +
                    "                \"acs:oss:*:*:*\" \n" +
                    "            ], \n" +
                    "            \"Effect\": \"Allow\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            try {
                // Add an endpoint. The STS endpoint is used. The first two parameters are not specified, indicating that the region ID is not required.
                DefaultProfile.addEndpoint("", "", "Sts", endpoint);
                // Construct a default profile. The parameter is not specified, indicating that the region ID is not required.
                IClientProfile profile = DefaultProfile.getProfile("", AccessKeyId, accessKeySecret);
                // Use the constructed profile to construct a client.
                DefaultAcsClient client = new DefaultAcsClient(profile);
                final AssumeRoleRequest request = new AssumeRoleRequest();
                request.setMethod(MethodType.POST);
                request.setRoleArn(roleArn);
                request.setRoleSessionName(roleSessionName);
                request.setPolicy(policy); // If the policy is not specified, the user obtains all permissions of the role.
                request.setDurationSeconds(1000L); // Set the validity period of the credential.
                final AssumeRoleResponse response = client.getAcsResponse(request);
                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: ");
                System.out.println("Error code: " + e.getErrCode());
                System.out.println("Error message: " + e.getErrMsg());
                System.out.println("RequestId: " + e.getRequestId());
            }
        }
    }
    The parameters are described as follows:
    • endpoint: the endpoint to access STS, such as sts.cn-hangzhou.aliyuncs.com. For more information about the endpoints to access STS in different regions, see Endpoints.
    • AccessKeyId and AccessKeySecret: the AccessKey pair saved in step 1.
    • RoleArn: the role ARN saved in step 3.
    • RoleSessionName: the name of the temporary access credential. We recommend that you use different application user names to distinguish the credentials.
    • Policy: the permission limits added to a user when the user assumes a role. For more information, see Implement access control based on RAM policies.
      Note The added policy is used to control the permissions of the temporary access credential after the user assumes a role. The permissions obtained by the temporary credential are restricted by both the role and the added policy. When a role is assumed, a policy can be added to further control the permissions. For example, when uploading files, you can add a policy to control upload paths for different users.
    • DurationSeconds: the validity period of the temporary access credential. Unit: seconds. Valid values: 900 to 3600.
  5. Access OSS by using the temporary access credentials.

    The following code provides an example on how to use the OSS SDK for Java to obtain a temporary access credential. For examples on how to use OSS SDKs for other languages, see the "Use STS for temporary access authorization" section in the "Authorized access" topic of Python, PHP, and Go.

    // The China (Hangzhou) region is used in this example as the endpoint. Specify the actual endpoint based on your requirements
    String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS, because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to https://ram.console.aliyun.com.
    String AccessKeyId = "<yourAccessKeyId>";
    String accessKeySecret = "<yourAccessKeySecret>";
    String securityToken = "<yourSecurityToken>";
    
    // After you obtain a temporary STS credential for your OSSClient, the OSSClient is generated based on the security token and temporary AccessKey pair (AccessKey ID and AccessKey secret).
    // Create an OSSClient instance. Note that the STS access credential generated in the preceding step is used.
    OSSClient ossClient = new OSSClient(endpoint, AccessKeyId, accessKeySecret, securityToken);
    
    // Perform operations in OSS.
    
    // Shut down the OSSClient instance.
    ossClient.shutdown();

FAQ

What can I do if NoSuchBucket error is reported when I obtain an access credential from STS?

This error occurs generally because the specified STS endpoint is incorrect. Enter a correct STS endpoint based on your region. For more information about the endpoints to access STS in different regions, see Endpoints.