Using a RAM (Resource Access Management) user's AccessKey pair to access OSS is more secure than using your Alibaba Cloud root account credentials, because you can grant the RAM user only the permissions it needs.
Prerequisites
Before you begin, ensure that you have:
An Alibaba Cloud account with RAM administrator access
An OSS bucket to upload objects to
Step 1: Create a RAM user
Log on to the RAM console using your Alibaba Cloud account or as a RAM administrator.
In the left-side navigation pane, choose Identities > Users.
On the Users page, click Create User.
In the User Account Information section, configure the following fields:
NoteTo create multiple RAM users at once, click Add User.
Field Description Logon Name Up to 64 characters. Can contain letters, digits, periods (.), hyphens (-), and underscores (_). Display Name Up to 128 characters. Tag Click the edit icon and enter a tag key and tag value. Tags help you categorize and manage RAM users. In the Access Mode section, select Using permanent AccessKey to access, then click OK.
Click Copy to save the AccessKey pair.
ImportantThe AccessKey secret is displayed only when the pair is first created. It cannot be retrieved later. Copy both the AccessKey ID and AccessKey secret to a secure location now. If you lose the secret, you must create a new AccessKey pair.
Step 2: Grant the RAM user permission to upload objects
Create a custom policy
In the left-side navigation pane, choose Permissions > Policies.
On the Policies page, click Create Policy.
On the Create Policy page, click the JSON tab and enter the following policy document. This example grants
oss:PutObjectpermission to theexampledirdirectory inexamplebucket.WarningThis example is for reference only. Configure fine-grained RAM policies based on your actual requirements to avoid granting excessive permissions. For details, 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/*" } ] }Click OK.
Set Policy Name to
RamTestPolicy, then click OK.
Attach the policy to the RAM user
In the left-side navigation pane, choose Identities > Users.
On the Users page, find the RAM user and click Add Permissions in the Actions column.
In the Grant Permission panel, click the Custom Policy tab, select
RamTestPolicy, then click OK.
Step 3: Upload an object using the RAM user's AccessKey pair
The following example uploads a local file (examplefile.txt) to exampledir/exampleobject.txt in examplebucket, using the Java SDK with Signature Version 4.
Set environment variables
Set the AccessKey pair as environment variables so the SDK loads credentials without hardcoding them in your code.
Linux/macOS:
export OSS_ACCESS_KEY_ID=<your-accesskey-id>
export OSS_ACCESS_KEY_SECRET=<your-accesskey-secret>Windows (Command Prompt):
setx OSS_ACCESS_KEY_ID "<your-accesskey-id>"
setx OSS_ACCESS_KEY_SECRET "<your-accesskey-secret>"Replace <your-accesskey-id> and <your-accesskey-secret> with the values you copied in Step 1.
Upload an object
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 {
// Endpoint for the China (Hangzhou) region. Replace with your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Load credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Bucket name.
String bucketName = "examplebucket";
// Full object path in the bucket. Do not include the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Full path to the local file to upload.
String filePath = "D:\\localpath\\examplefile.txt";
// Region where the bucket is located.
String region = "cn-hangzhou";
// Create an OSSClient instance with Signature Version 4.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
PutObjectResult result = ossClient.putObject(putObjectRequest);
} catch (OSSException oe) {
System.out.println("OSS rejected the request: " + 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("Client error (e.g., network issue): " + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}For examples in other languages, see:
FAQ
Where can I view my AccessKey ID? Can I retrieve the AccessKey secret later?
I'm getting an AccessDenied error when uploading. What should I check?
How do I identify a specific error type?
I'm getting a NoSuchBucket error. What's wrong?
I'm getting "The bucket you are attempting to access must be addressed using the specified endpoint." What's wrong?
What's next
To share uploaded objects with third parties without exposing your credentials, generate presigned URLs that allow temporary access. See Download an object by using a presigned URL.