All Products
Search
Document Center

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

Last Updated:Jan 26, 2024

You can use Security Token Service (STS) to generate temporary access credentials to authorize a 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

One of the following accounts is available: an Alibaba Cloud account or a Resource Access Management (RAM) user to which the AliyunRAMFullAccess policy is attached. For more information about how to grant permissions to a RAM user, see Grant permissions to a RAM user.

Scenarios

Assume that you are a mobile app developer and plan to store the user data of an app in OSS. The data of each user must be isolated to prevent users from obtaining data of other users. In this case, you can use STS to authorize users to access their own data in your OSS buckets.

The following figure shows how to use STS to authorize a user to access OSS.

sts

  1. The app user logs on to the app server. The username and password used by the app user for logon are different from the AccessKey pair of the Alibaba Cloud account used to access OSS. The app server must determine the minimum access permissions for each valid app user.

  2. The app server sends a request to STS to obtain a security token. Before the app server sends the request to STS, the app server must determine the minimum access permissions required by the app user to access OSS and the validity period of the credentials. You can configure a RAM policy to customize the minimum access permissions. Then, the app server calls AssumeRole to obtain a security token, which authenticates the identity of a role.

  3. STS returns temporary access credentials to the app server. The credentials consist of a security token and a temporary AccessKey pair that can be used to access OSS within a validity period. A temporary AccessKey pair consists of an AccessKey ID and an AccessKey secret.

  4. The app server returns the temporary access credentials to the app client. The app client can cache the credentials. After the credentials expire, the app client must apply for new temporary access credentials from the app server. For example, if the temporary access credentials are valid for 1 hour, the app client can send a request to the app server to update the credentials every 30 minutes.

  5. The app client uses the locally cached temporary access credentials to initiate a request to call OSS API operations. After OSS receives the request, OSS uses STS to verify the access credentials in the request and responds to the request.

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. On the page that appears, click Copy to save the AccessKey pair of the RAM user.

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

  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.image.png

  3. Click OK.

Step 3: Create a role used to obtain temporary access credentials from STS

  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 role the permissions to upload objects to OSS

  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 Add Permissions in the Actions column.

    4. In the Add Permissions panel, click the Custom Policy tab and select the RamTestPolicy policy.

    5. Click OK.

Step 5: Obtain temporary access credentials

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.        
        String endpoint = "yourStsEndpoint";
        // 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 temporary access credentials to upload objects only 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" +
                "}";
        // Set the validity period of the temporary access credentials to 3,600 seconds. 
        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 V3.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 V3.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 V3.12.0 or later. 
            request.setSysMethod(MethodType.POST);
            // You can specify this parameter by using STS SDK for Java that is earlier than V3.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());
        }
    }
}

Parameter

Example

Description

endpoint

sts.cn-hangzhou.aliyuncs.com

The endpoint of STS. You can access STS over the Internet or a virtual private cloud (VPC). For more information about STS endpoints, see Endpoints.

accessKeyId

LTAI5tJHezdULrXcczCW****

The AccessKey ID generated for the RAM user in Step 1.

accessKeySecret

CTkGhP9xUpMR5IWj4WRZTQ2SR****

The AccessKey secret generated for the RAM user in Step 1.

roleArn

acs:ram::137918634****:role/ramosstest

The role ARN obtained in Step 3.

roleSessionName

SessionTest

The name of the role session.

You can specify this parameter based on your business requirements. In most cases, you can set this parameter to the identity of the user who calls API operations.

The name must be 2 to 64 characters in length and can contain letters, digits, periods (.), at signs (@), hyphens (-), and underscores (_).

policy

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

The policy that specifies the permissions of the returned STS token. This allows you to implement more fine-grained access control. The following descriptions provide the details:

  • If you specify this parameter, the permissions that are granted to the STS token are the intersection of the RAM role permissions and the permissions that are specified in this parameter.

  • If you do not specify this parameter, the STS token has all permissions of the RAM role.

For more information about how to configure the elements in a policy, see Overview.

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 the Action element, see Overview.

durationSeconds

3600

The validity period of the temporary access credentials.

Unit: seconds. Minimum value: 900. The maximum value is based on the maximum session duration of 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. For more information, see Specify the maximum session duration for a RAM role.

In time-consuming scenarios or when large objects need to be uploaded, we recommend that you specify a long validity period for temporary access credentials. This way, you do not need to frequently use STS to generate temporary access credentials.

Use RESTful APIs

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

Step 6: Use the temporary access credentials to upload objects 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 {
// In this example, the endpoint of the China (Hangzhou) region is used. 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 signed 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 occurs?

The error occurs 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 a policy is correctly configured. For example, the configuration of the Resource field may not be complete. For more information about the elements in a policy, see Overview.

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. 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 in Step 5. Refer to the following examples to check whether the required permissions are overlapped between the permissions granted in these two steps.

  • Example 1

    If the AliyunOSSFullAccess policy is attached to the role in Step 4 and the oss:PutObject permission is configured in Step 5, the temporary access credentials have the oss:PutObject permission. This means that you can only upload objects to the specified bucket.

  • Example 2

    If the oss:PutObject system permission is granted to the role in Step 4 and the oss:GetObject permission is configured in Step 5, the temporary access credentials do not have any permissions. This means that you cannot perform any operations on the specified bucket.

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 have multiple sets of valid temporary access credentials at the same time?

Yes, you can have multiple sets of valid 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 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. The time must be in UTC. For example, use 2014-05-26T12:00:00Z to specify May 26, 2014, 20:00:00 (UTC+8).