All Products
Search
Document Center

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

Last Updated:Apr 18, 2024

You can use Security Token Service (STS) to generate temporary access credentials to authorize a RAM user to access your Object Storage Service (OSS) resources within a specific period of time. This way, you do not need to share your AccessKey pair. This ensures higher data security.

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 OpenAPI Access. Then, click OK.

  6. Complete security verification as prompted.

  7. Copy the AccessKey pair of the RAM user.

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

After you create the RAM user, you must grant the RAM user the permissions to call the STS API operation by assuming a RAM role.

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

  2. In the Add Permissions panel, click the System Policy tab and select the AliyunSTSAssumeRoleAccess policy.

    Note

    The RAM user is attached the AliyunSTSAssumeRoleAccess policy to call the AssumeRole operation of STS. The permissions of the AliyunSTSAssumeRoleAccess policy are independent of the permissions required to obtain temporary access credentials and initiate OSS requests by using temporary access credentials.

    image.png

  3. Click OK.

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 Create Role panel, set Select Trusted Entity to Alibaba Cloud Account and click Next.

  3. In the Create Role panel, 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 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 upload only 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. Edit the script in the policy editor to grant the role the permissions to upload objects to the src and dest directories in the examplebucket bucket. The following code provides an example on how to grant the role the permissions.

      Warning

      The following example 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 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/src/*",
                   "acs:oss:*:*:examplebucket/dest/*"
                 ]
           }
          ]
      }
    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 of the RamOssTest role.

    4. In the Grant Permission panel, click the Custom Policy tab and select the RamTestPolicy policy.

    5. Click OK.

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

After you grant the RAM user the permissions to upload objects to OSS, the RAM user assumes the RAM role to obtain temporary access credentials. Temporary access credentials include security token (SecurityToken), temporary access key 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 that have the simple upload (oss:PutObject) permission, see STS SDK overview.

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";   
        // The following policy allows users to use only temporary access credentials to upload objects to the src directory of the examplebucket bucket. 
        // The permissions of the temporary access credentials are the intersection of the role permissions configured in Step 4 and the permissions specified by the RAM policy. Users can use the temporary access credentials to upload objects only to the src directory in the examplebucket bucket. 
        // If the policy is empty, the user is granted all permissions of the role.       
        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" +
                "}";
        // Specify the validity period of the temporary access credentials. Unit: seconds. The minimum value is 900. The maximum value is based on 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 destination task is complete. 
        Long durationSeconds = 3600L;
        try {
            // regionId specifies the region ID of the RAM user. For example, if the RAM user is located in the China (Hangzhou) region, set regionId to cn-hangzhou. You can also retain the default setting, which is an empty string (""). 
            String regionId = "";
            // Add the endpoint. You can specify this parameter by using STS SDK for Java 3.12.0 or later. 
            DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
            // Add 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());
        }
    }
}

For more information about STS endpoints, see Endpoints.

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 expires, use the temporary access credentials to upload an local file to OSS.

The following sample code provides an example on how to use OSS SDK for Java 3.12.0 to upload a local file named exampletest.txt from D:\\localpath to the src directory in a bucket named examplebucket:

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. In this example, the endpoint of the China (Hangzhou) region is used. Example: 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 the exampletest.txt file to the src directory of the examplebucket bucket. 
PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket", "src/exampletest.txt", new File("D:\\localpath\\exampletest.txt"));

// ObjectMetadata metadata = new ObjectMetadata();
// Specify the storage class when you upload the file. 
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// Specify the access control list (ACL) when you upload the file. 
// 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();
        }
    }
}
}

For more information about the storage class that you can specify for an object when you upload the object, see Overview. For more information about the ACL that you can specify for an object when you upload the object, see Object ACLs.

For more information about examples on OSS SDKs for other programming languages, see the following topics:

For more information about how to obtain the URL of an uploaded object, see Share objects with object URLs.

FAQ

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

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

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

Use the temporary AccessKey pair 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 use a specific method to obtain temporary access credentials in Step 5. 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. Check whether the specified bucket exists. If the specified bucket does not exist, specify an existing bucket.

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 from STS to access OSS resources?

Check whether the RAM policy is correctly configured. For more information about the requirements for each element in the 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, configure the Action element in the policy based on the operations. 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 from STS to perform operations on OSS resources?

The error message is returned because you do not have the permissions to perform related operations. Before you apply for temporary access credentials, you must create a RAM role to obtain the temporary access credentials and grant 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 RAM role and 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 credential has the same policy as the RAM role.

What do I do if the The bucket you are attempting to access must be addressed using the specified endpoint. error message 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 temporary access credentials at the same time?

Yes. 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 that are obtained by sending multiple requests to STS within the validity periods of the temporary access credentials.

What do I do if I receive an invalid time format error?

If an invalid 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 OSS-related operations. For more information about the solution, see 0003-00000301.

References

You can upload data directly to OSS from clients by using temporary access credentials from STS. For more information, see Overview.