All Products
Search
Document Center

Object Storage Service:Use the AccessKey pair of a RAM user to access OSS

Last Updated:Oct 08, 2026

You can grant specific permissions to a RAM user and use the AccessKey pair of the RAM user to access your OSS resources over the long term. Compared with using an Alibaba Cloud account AccessKey pair, using a RAM user AccessKey pair to access OSS resources is more secure.

Step 1: Create a RAM user

  1. Sign in to the RAM console using your Alibaba Cloud account or as a RAM user with administrative permissions (a user to which the AliyunRAMFullAccess policy is attached).

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

  3. On the Users page, click Create User.

  4. On the Create User page, in the User Account Information section, configure the user's basic information.

    • Logon Name (required): Up to 64 characters. Allows letters, digits, periods (.), hyphens (-), and underscores (_).

    • Display Name (optional): The name can be up to 128 characters long.

    • Tag (optional): Click edit, then enter a tag key and tag value to categorize and manage users.

    Note

    Click Add User to create multiple RAM users in bulk.

  5. In the Access Mode section, select an access mode based on the user type.

    Important
    • As a security best practice, select only one access mode per user to separate human console access from programmatic application access. If a RAM user needs both console sign-in and API call capabilities, you can select both access modes. After you select Permanent AccessKey, you must select the I confirm that I must create an AccessKey checkbox to continue.

    • A leaked AccessKey pair compromises your account. Use Security Token Service (STS) tokens (temporary credentials) instead to reduce risk. Best practices for using access credentials to call Alibaba Cloud APIs.

    Console access

    Select Console Access.

    Programmatic access

    Select Permanent AccessKey.

    The system automatically creates an AccessKey ID and AccessKey secret for the RAM user.

    Important

    The AccessKey secret is displayed only at creation and cannot be retrieved later. You must immediately download or copy and save the AccessKey secret. A leaked AccessKey pair compromises all resources under your account. Create an AccessKey pair.

Step 2: Grant the RAM user the permissions to upload objects

  1. Create a custom policy for uploading objects.

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

    2. Click Create Policy.

    3. On the Create Policy page, click Edit Script, and then enter a policy in the policy document input box to grant the RAM user the permissions to upload objects to the exampledir directory in the destination bucket examplebucket. The following sample configuration is provided for your reference.

      Warning

      The following example is for reference only. You must configure a more fine-grained authorization policy based on your actual needs to prevent the risk of excessive permissions. For information about more fine-grained authorization policy configuration, see Use RAM policies or STS to grant other users permissions.

      {
        "Version": "1",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "oss:PutObject",
            "Resource": "acs:oss:*:*:examplebucket/exampledir/*"
          }
        ]
      }
    4. After the policy is configured, click Continue to Edit Basic Information.

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

  2. Grant the custom policy to the RAM user.

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

    2. On the Users page, find the target RAM user.

    3. Click Add Permissions on the right side of the RAM user.

    4. On the Add Permissions page, click the Custom Policy tab, and select the custom policy you created: RamTestPolicy.

    5. Click Confirm Authorization.

Step 3: Use the RAM user AccessKey pair to upload an object to OSS

The following Java sample code uploads the local file examplefile.txt to the exampledir directory in the destination bucket examplebucket as exampleobject.txt.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.File;

public class Demo {

    public static void main(String[] args) throws Exception {
        // 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 access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the key in PutObjectRequest, which is the complete object name. Do not include the bucket name, for example, exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. 
        // By default, if the path of the local file is not specified, the local file is uploaded from the path of the project to which the sample program belongs. 
        String filePath= "D:\\localpath\\examplefile.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";
        
        // Create an OSSClient instance. 
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create a PutObjectRequest object. 
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // The following sample code provides an example on how to specify the storage class and ACL of an object when you upload 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. 
            PutObjectResult result = 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());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

FAQ

How do I view the AccessKey pair of a RAM user? Can I view the old AccessKey Secret?

Use an existing AccessKey pair or create one. For more information, see Create an AccessKey. Note: To reduce the risk of AccessKey leaks, the AccessKey Secret is displayed only once when created and cannot be viewed afterward. Make sure to keep it safe.

How do I troubleshoot the AccessDenied error when uploading objects by using the AccessKey pair of a RAM user?

The AccessDenied error when uploading objects is usually caused by using incorrect AccessKey information or not granting the RAM user the permissions to upload objects. You can troubleshoot the issue by performing the following steps:

  1. Verify that the AccessKey pair of the RAM user is correct. Use an existing AccessKey pair or create one. For more information, see Create an AccessKey. Note: To reduce the risk of AccessKey leaks, the AccessKey Secret is displayed only once when created and cannot be viewed afterward. Make sure to keep it safe.

  2. Log on to the RAM console, select the specific user, and grant the RAM user the permissions to upload objects to OSS.

How do I query specific error types when errors occur?

For information about querying error types, see the OSS Error codes documentation. For example, for common authentication errors, see 02-AUTH.

How do I handle the NoSuchBucket error?

This error occurred because the specified bucket does not exist. Check and specify the correct bucket name.

How do I handle the The bucket you are attempting to access must be addressed using the specified endpoint. error?

This error occurred because the endpoint parameter is incorrect. You must specify the correct endpoint based on the region where the bucket is located. For information about the mapping between regions and endpoints, see Regions and endpoints.

Related Documentation