All Products
Search
Document Center

Object Storage Service:Use temporary access credentials provided by STS to access OSS

更新時間:Dec 15, 2024

Security Token Service (STS) can grant a RAM user time-limited access to the specified resources in Object Storage Service (OSS) by issuing temporary access credentials to the RAM user. After the temporary access credentials expire, the RAM user cannot access the resources by using the temporary access credentials. STS helps improve flexibility and timeliness of access control.

Prerequisites

A bucket is created. For more information, see Create a bucket.

Step 1: Create a RAM user

  1. Log on to the RAM console.

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

  3. On the Users page, click Create User.

  4. Configure the Logon Name and Display Name parameters.

  5. In the Access Mode section, select Using permanent AccessKey to access. Then, click OK.

  6. Complete security verification as prompted.

  7. Copy the AccessKey pair (AccessKey ID and AccessKey secret).

    Important

    You can obtain the AccessKey secret of a RAM user only when you create the RAM user. You must keep the AccessKey secret safely to prevent credential leaks.

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

After you create the RAM user, grant the RAM user the permissions to call the AssumeRole operation of STS.

  1. On the Users page, find the RAM user that you created and click Add Permissions in the Actions column.

  2. In the Policy section of the Grant Permission panel, select the AliyunSTSAssumeRoleAccess policy.

    Note

    The AliyunSTSAssumeRoleAccess policy allows a RAM user to call the AssumeRole operation. The permissions of the policy are independent of the permissions required for the RAM user to obtain temporary access credentials from STS and initiate requests to OSS.

    image.png

  3. Click Grant permissions.

Step 3: Create a RAM role

Create a RAM role to declare the permissions of the RAM role when the RAM role is assumed.

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

  2. Click Create Role. In the Select Role Type step of the Create Role wizard, set Select Trusted Entity to Alibaba Cloud Account and click Next.

  3. In the Configure Role step of the Create Role wizard, set RAM Role Name to RamOssTest and Select Trusted Alibaba Cloud Account to Current Alibaba Cloud Account.

  4. Click OK. After the role is created, click Close.

  5. On the Roles page, enter RamOssTest in the search box, click the search icon, and click RamOssTest in the search result.

  6. Click Copy on the right side of the RamOssTest page to save the Alibaba Cloud Resource Name (ARN) of the role.arn

Step 4: Grant the RAM role the permissions to upload objects to OSS

Attach one or more policies to the RAM role to grant the RAM role the permissions to perform operations on OSS resources when the RAM role is assumed. For example, if you want a RAM user to assume this RAM role and only upload objects to a specific OSS bucket, you must attach a policy that grants write permissions to the RAM role.

  1. Create a custom policy to grant the role the permissions to upload objects.

    1. In the left-side navigation pane, choose Permissions > Policies.

    2. On the Policies page, click Create Policy.

    3. On the Create Policy page, click JSON. Enter the following script in the code editor to grant the RAM role the permissions to upload objects to the examplebucket bucket.

      Warning

      The following example is only for reference. You must configure fine-grained RAM policies based on your requirements to prevent granting excessive permissions to users. For more information about how to configure fine-grained RAM policies, see Example 9: Use RAM or STS to authorize users to access OSS resources.

      {
          "Version": "1",
          "Statement": [
           {
                 "Effect": "Allow",
                 "Action": [
                   "oss:PutObject"
                 ],
                 "Resource": [
                   "acs:oss:*:*:examplebucket/*"             
                 ]
           }
          ]
      }
      Note

      The Action element specifies the permissions that you want to grant to the RAM role. For example, if you specify oss:PutObject, the RAM user that assumes the RAM role can upload objects to the specified bucket by using various upload methods, such as simple upload, form upload, append upload, multipart upload, and resumable upload. For more information, see Action element in RAM policies for OSS.

    4. Click Next to edit policy information.

    5. In the Basic Information section, set Name to RamTestPolicy and click OK.

  2. Attach the custom policy to the RamOssTest role.

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

    2. On the Roles page, find the RamOssTest role.

    3. Click Grant Permission in the Actions column.

    4. In the Grant Permission panel, select Custom Policy from the drop-down list in the Policy section and select the RamTestPolicy policy.

    5. Click Grant permissions.

Step 5: Use the RAM user to assume the RAM role to obtain temporary access credentials

After you grant the RAM role the permissions to upload objects to OSS, the RAM user assumes the RAM role to obtain temporary access credentials. Temporary access credentials include a security token (SecurityToken), temporary AccessKey pair (AccessKey ID and AccessKey secret), and validity period (Expiration).

Use STS SDKs

You can use STS SDKs to obtain temporary access credentials.

The following sample code provides an example on how to use STS SDK for Java to obtain temporary access credentials that have the simple upload (oss:PutObject) permission. For more information about how to use STS SDKs for other programming languages to obtain temporary access credentials, see STS SDK overview. For a list of STS endpoints, see Endpoints.

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.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
public class StsServiceSample {
    public static void main(String[] args) { 
        // Specify the endpoint of STS. Example: sts.cn-hangzhou.aliyuncs.com. You can access STS over the Internet or a virtual private cloud (VPC).        
        String endpoint = "sts.cn-hangzhou.aliyuncs.com";
        // Obtain the AccessKey ID and AccessKey secret of the RAM user generated in Step 1 from environment variables. 
        String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET");
        // Obtain the ARN of the RAM role generated in Step 3 from environment variables. 
        String roleArn = System.getenv("OSS_STS_ROLE_ARN");
        // Specify a custom role session name to distinguish different tokens. Example: SessionTest.         
        String roleSessionName = "yourRoleSessionName";   
        // Specify that the temporary access credentials have all permissions of the RAM role.       
        String policy = null;
        // Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period is 900 seconds. The maximum validity period is the same as the maximum session duration specified for the current role. The maximum session duration of the current role ranges from 3,600 seconds to 43,200 seconds. The default maximum session duration of the current role is 3,600 seconds. 
        // In large object upload or other time-consuming scenarios, we recommend that you set the validity period of temporary access credentials to a reasonable value to ensure that you do not need to repeatedly call the STS API operation to obtain temporary access credentials before the task is complete. 
        Long durationSeconds = 3600L;
        try {
            // Specify the region of STS. We recommend that you keep the default value. The default value is an empty string (""). 
            String regionId = "";
            // Specify the endpoint. You can specify this parameter by using STS SDK for Java 3.12.0 or later. 
            DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
            // Specify the endpoint. You can specify this parameter by using STS SDK for Java that is earlier than 3.12.0. 
            // DefaultProfile.addEndpoint("",regionId, "Sts", endpoint);
            // Create a default profile. 
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            // Use the profile to create a client. 
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            // You can specify this parameter by using STS SDK for Java 3.12.0 or later. 
            request.setSysMethod(MethodType.POST);
            // You can specify this parameter by using STS SDK for Java that is earlier than 3.12.0. 
            // request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); 
            request.setDurationSeconds(durationSeconds); 
            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());
        }
    }
}
Important

After temporary access credentials obtain permissions from a RAM role, you can further limit the permissions of the temporary access credentials. For example, if the temporary access credentials have the permissions to upload objects to the examplebucket bucket, you can refer to the following sample policy to specify that the access credentials can be used to upload data only to a specific directory in the bucket.

// The following policy specifies that the temporary access credentials can be used to upload objects only to the src directory of the examplebucket bucket. 
// The final permissions granted to the temporary access credentials are the intersection of the role permissions that are specified in Step 4 and the permissions that are specified in the policy. This allows you to upload objects only to the src directory in the examplebucket bucket.       
String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:PutObject\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:examplebucket/src/*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";

Use RESTful APIs

You can call the AssumeRole operation of STS to obtain temporary access credentials.

Step 6: Use the temporary access credentials to upload objects to OSS

Before the validity period (Expiration) of the temporary access credentials ends, use the temporary access credentials to upload local files to OSS.

Note
  • The expiration time of the temporary access credentials is in UTC, which is 8 hours earlier than the UTC+8 time zone that is used in China. For example, if the expiration time of temporary access credentials is 2024-04-18T11:33:40Z, the temporary access credentials expire on April 18, 2024 at 19:33:40 (UTC+8).

  • You can use temporary access credentials multiple times before they expire. For example, before temporary access credentials expire, you can use them to repeatedly call upload operations to upload multiple files or upload a package of the files.

The following sample code provides an example on how to upload the exampletest.txt file from the local path D:\\localpath to the examplebucket bucket by using OSS SDK for Java 3.12.0. For more information about how to use temporary access credentials to upload data by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyuncs.exceptions.ClientException;

import java.io.File;

public class Demo {
    public static void main(String[] args) throws ClientException {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain the temporary AccessKey pair generated in Step 5 from environment variables. 
String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET");
// Obtain the security token generated in Step 5 from environment variables. 
String securityToken = System.getenv("OSS_SESSION_TOKEN");

// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
// Upload a local file named exampletest.txt to examplebucket. 
PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket", "exampletest.txt", new File("D:\\localpath\\exampletest.txt"));

// ObjectMetadata metadata = new ObjectMetadata();
// Specify the storage class of the uploaded object. 
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// Specify the access control list (ACL) of the uploaded object. 
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

try {
     // Upload the local file. 
     ossClient.putObject(putObjectRequest);
    } catch (OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        System.out.println("Error Message:" + oe.getErrorMessage());
        System.out.println("Error Code:" + oe.getErrorCode());
        System.out.println("Request ID:" + oe.getRequestId());
        System.out.println("Host ID:" + oe.getHostId());
    } finally {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
}
}

FAQ

What do I do if the You are not authorized to do this action. You should be authorized by RAM. error message is returned?

A RAM user must use its AccessKey pair (AccessKey ID and AccessKey secret), not the AccessKey pair of the Alibaba Cloud account, to assume the RAM role to obtain temporary access credentials.Step 5: Use the RAM user to assume the RAM role to obtain temporary access credentials

What do I do if error message The Min/Max value of DurationSeconds is 15min/1hr. is returned?

The error is returned because the validity period of the temporary access credentials does not fall within the expected range. Specify the validity period based on the following rules:

  • If the default maximum session duration (3,600 seconds) is used, the minimum validity period is 900 seconds and the maximum validity period is 3,600 seconds.

  • If a custom maximum session duration is specified, the minimum validity period is 900 seconds and the maximum validity period is the specified maximum session duration. The value range of the role session duration is 3600 to 43200 seconds.

You can check the maximum session duration in the RAM console. For more information, see View the information about a RAM role.

What do I do if error message The security token you provided is invalid. is returned?

Make sure that you specify the security token obtained in Step 5.

What do I do if error message The OSS Access Key Id you provided does not exist in our records. is returned?

Use the temporary AccessKey pair of the RAM user to apply for new temporary access credentials from the app server because the current temporary access credentials have expired. For more information, see Step 5.

What do I do if the AccessDenied: Anonymous access is forbidden for this operation. error message is returned?

The error message is returned because you specify the AccessKey ID and AccessKey secret of your Alibaba Cloud account when you obtain temporary access credentials in Step 5. You must specify the AccessKey ID and AccessKey secret generated for the RAM user in Step 1.

What do I do if the NoSuchBucket error code is returned?

The error code is returned because the specified bucket does not exist. Make sure that the specified bucket exists.

What do I do if the You have no right to access this object because of bucket acl. error message is returned when I use the temporary access credentials to access OSS resources?

Check whether the RAM policy is correctly configured. For more information about elements in a RAM policy, see RAM policies. If you want to obtain temporary access credentials that can be used to perform specific operations, such as multipart upload and append upload, specify the corresponding permissions in the Action element of the policy. For more information about OSS actions, see Action element in RAM policies for OSS.

What do I do if the Access denied by authorizer's policy. error message is returned when I use the temporary access credentials obtained from STS to perform operations on OSS resources?

The error message is returned because you do not have the permissions to perform the operations. Before you apply for temporary access credentials, you must create a RAM role and grant the required permissions to the RAM role. For more information, see Step 4. When you initiate a request to the STS server to assume this RAM role to obtain temporary access credentials, you can use the policy parameter to further restrict the permissions of the temporary access credentials. For more information, see Step 5.

  • If you specify the policy parameter, the final permissions of the temporary access credentials are the intersection of the permissions of the RAM role and the permissions that are specified by the policy parameter.

    • Example 1

      In the following figure, A indicates the permissions of the RAM role, B indicates the permissions specified by the policy parameter, and C is the final permissions of the temporary access credentials.

      1.jpg

    • Example 2

      In the following figure, A indicates the permissions of the RAM role, and B indicates the permissions specified by the policy parameter. The permissions specified by the policy parameter are a subset of the permissions of the RAM role. Therefore, B is the final permissions of the temporary access credentials.

      2.jpg

  • If you do not set the policy, the temporary access credentials have the same permissions as the RAM role.

What do I do if error message The bucket you are attempting to access must be addressed using the specified endpoint. is returned?

The error message is returned because the value that you specified for the Endpoint parameter in Step 6 is invalid. Specify the Endpoint parameter based on the region in which the bucket is located. For more information about regions and endpoints, see Regions and endpoints.

Can I obtain multiple sets of temporary access credentials at the same time?

Yes, you can obtain multiple sets of temporary access credentials at the same time. You can obtain a set of temporary access credentials by sending a request to STS. If you want to obtain multiple sets of temporary access credentials from STS, send multiple requests to STS. You can simultaneously use multiple sets of temporary access credentials within the validity periods of the temporary access credentials.

What do I do if I receive a time format error?

If a time format error is returned, a possible cause is unnecessary spaces between characters in the value of the Timestamp parameter.

Specify the time in the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format. For example, use 2014-05-26T12:00:00Z to specify May 26, 2014, 20:00:00 (UTC+8).

What do I do if the 0003-0000301 error code is returned?

The 0003-0000301 error code is returned because the temporary access credentials do not have the permissions to perform the specified operations. You can follow the instructions in the 0003-00000301 topic to resolve the issue.

References

  • You can use temporary access credentials to upload data to OSS directly from your client and specify upload conditions, such as the file size, file types, and destination directories. For more information, see Direct client uploads.

  • You can use signed URLs to share objects that are uploaded by using temporary access credentials. For more information, see Share objects with object URLs.