You can use Alibaba Cloud Security Token Service (STS) to authorize temporary access to OSS. You can use STS to grant a third-party application or your RAM user an access credential that has custom permissions and a custom validity period.

Operation

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 to grant OSS access permissions to federated users without providing your long-term keys (such as logon passwords and AccessKey pairs) of your Alibaba Cloud accounts or RAM users. You can customize the access permissions and validity period of the credential. The temporary access credential 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 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. If you are a mobile app developer and plan to use Alibaba Cloud OSS to store 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 permissions to users.

  1. Log on as the app user. An app user is a 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 application server requests a security token from STS. Before the app calls 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 credential. 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, a temporary AccessKey pair, 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 OSS receives the request, OSS uses STS to verify the access credential in the request and responds to the request.

Procedures

After you combine OSS SDKs and STS SDKs, you can access OSS by using a temporary access credential provided by STS. For example, 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.
    7. Select the created RAM user. Click Add Permissions.
    8. In the Add Permissions panel, add the AliyunSTSAssumeRoleAccess policy to the 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 RAM 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, to authorize users to upload objects to the ram-test/examplefolder folder, you can select Script and add the following script in the Policy Document section.
      Warning The following script is for reference only. You must configure fine-grained RAM policies based on your requirements to avoid granting excessive permissions to users. For more information about how to configure fine-grained RAM policies, see the Example 5: Use RAM or STS to grant other users permissions to access OSS resources section in the Implement access control based on RAM policies topic.
      {
          "Version": "1",
          "Statement": [
           {
                 "Effect": "Allow",
                 "Action": [
                   "oss:PutObject"
                 ],
                 "Resource": [
                   "acs:oss:*:*:ram-test/examplefolder",
                   "acs:oss:*:*:ram-test/examplefolder/*"// Authorize users to access the lowest-level folders under the examplefolder folder.
                 ]
           }
          ]
      }
  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 panel, enter a RAM role name in the RAM Role Name field and a note in the Note field. 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 panel, select Custom Policy and add the policy that you created in Step 2.
      After the policy is added, the following page appears.
    8. Copy the ARN of the created role, which is the ID of the role.
  4. Obtain an STS AccessKey pair and a security token.

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

    The following code provides an example on how to use OSS SDK for Java 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, which indicates that the region ID is not required.
                DefaultProfile.addEndpoint("", "", "Sts", endpoint);
                // Construct a default profile. The first parameter is not specified, which indicates 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 following parameters are used in the preceding code:
    • endpoint: the endpoint used 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 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 you upload objects, you can add a policy to control upload paths for different users.
    • DurationSeconds: the validity period of the temporary access credential. The minimum value is 900. The maximum value is the maximum session duration that the current role specifies. Unit: seconds. For more information, see Set the maximum session duration for a RAM role.
  5. Access OSS by using the temporary access credentials.

    The following code provides an example on how to use OSS SDK for Java to upload a local file to OSS:

    // The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
    String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // Security risks may arise if you log on with the AccessKey pair of an Alibaba Cloud account 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 the RAM console.
    String AccessKeyId = "<yourAccessKeyId>";
    String accessKeySecret = "<yourAccessKeySecret>";
    String securityToken = "<yourSecurityToken>";
    
    // After you obtain a temporary STS credential for your OSSClient, an OSSClient instance is created based on the security token and temporary AccessKey pair (AccessKey ID and AccessKey secret) that are contained in the credential.
    // 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);
    // Create a PutObjectRequest object.
    PutObjectRequest putObjectRequest = new PutObjectRequest("<yourBucketName>", "<yourObjectName>", new File("<yourLocalFile>"));
    
    // Optional. Specify the storage class and ACL of the object.
    // ObjectMetadata metadata = new ObjectMetadata();
    // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
    // metadata.setObjectAcl(CannedAccessControlList.Private);
    // putObjectRequest.setMetadata(metadata);
    
    // Upload the local file.
    ossClient.putObject(putObjectRequest);
    
    // Shut down the OSSClient instance.
    ossClient.shutdown();
    For more examples of OSS SDKs for other programming languages, see the following topics:

FAQ

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

The error message returned because the specified STS endpoint is invalid. Enter a valid STS endpoint based on your region. For more information about the endpoints to access STS in different regions, see Endpoints.