All Products
Search
Document Center

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

Last Updated:Dec 05, 2025

You can grant permissions to a RAM user and use the AccessKey pair of the RAM user to access OSS resources. When you access OSS resources, we recommend that you use the AccessKey pair of a RAM user instead of an Alibaba Cloud account to ensure higher access security.

Step 1: Create a RAM user

  1. Log on to the RAM console by using an Alibaba Cloud account or as a RAM administrator.

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

  3. On the Users page, click Create User. image

  4. In the User Account Information section of the Create User page, configure the following parameters:

    • Logon Name: The logon name can be up to 64 characters in length, and can contain letters, digits, periods (.), hyphens (-), and underscores (_).

    • Display Name: The display name can be up to 128 characters in length.

    • Tag: Click the edit icon and enter a tag key and a tag value. Adding tags helps you categorize and manage RAM users.

    Note

    You can click Add User to create multiple RAM users at a time.

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

  6. Click Copy to save the AccessKey pair of the RAM user.

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

  1. Create a custom policy to grant 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 the JSON tab. Enter the policy document to grant the role the permissions to upload objects to the exampledir directory of the examplebucket bucket. The following sample code shows how to grant the role the permissions.

      Warning

      The following example is provided for reference only. You need to configure fine-grained RAM policies based on your requirements to avoid granting excessive permissions. 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/exampledir/*"
          }
        ]
      }
    4. After you configure the policy, click OK.

    5. Set Policy Name to RamTestPolicy and click OK.

  2. Attach the custom policy to a RAM user.

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

    2. On the Users page, find the RAM user to which you want to attach the custom policy.

    3. On the Users page, click Add Permissions in the Actions column of the RAM user.

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

    5. Click OK.

Step 3: Use the AccessKey pair of the RAM user to upload objects to OSS

The following sample code provides an example on how to upload a local file named examplefile.txt to the exampledir directory of examplebucket. After the local file is uploaded, the object in the exampledir directory is named 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 full path of the object. Do not include the bucket name in the full path. 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 ID of a RAM user? Can I view the AccessKey secret of an AccessKey pair?

  1. For information about how to view the AccessKey pair of a RAM user, see View the information about AccessKey pairs of a RAM user.

  2. The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey pair at a later time. If you forget the AccessKey secret, you cannot retrieve the AccessKey secret. In this case, you can directly create a new AccessKey pair for rotation in the RAM console. For more information, see Create an AccessKey pair.

How do I fix an AccessDenied error that occurs when I use the AccessKey pair of a RAM user to upload files?

The AccessDenied error occurs typically for two reasons: wrong AccessKey pair or a lack of upload permissions. You can perform the following steps to troubleshoot the AccessDenied error:

  1. Check whether the provided AccessKey pair is correct by following the instructions described in View the information about AccessKey pairs of a RAM user.

  2. The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey pair at a later time. Once lost, the AccessKey secret cannot be retrieved. In this case, you can directly create a new AccessKey pair for rotation in the RAM console. For more information, see Create an AccessKey pair.

  3. In the RAM console, check whether the RAM user has the permission to upload files to OSS. If not, grant the required permissions.

If an error is reported, how do I determine the specific type of the error?

OSS provides Error codes to help you determine the specific type of an error. For example, you can see 02-AUTH for common authentication errors.

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 you specify an existing bucket.

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

This error message is returned because you specified an invalid endpoint. Specify a valid endpoint based on the region in which the bucket is located. For more information about the regions and endpoints, see Regions and endpoints.

Reference

  • To facilitate controlled access by third parties, you can generate presigned URLs that allow temporary preview or download of uploaded objects. For more information, see Download an object by using a presigned URL.