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
Log on to the RAM console by using an Alibaba Cloud account or a RAM user who has administrative rights.
In the left-side navigation pane, choose .
On the Users page, click Create User.
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
icon and enter a tag key and a tag value. You can add one or more tags to the RAM user. This way, you can manage the RAM user based on the tags.
NoteYou can click Add User to create multiple RAM users at a time.
In the Access Mode section, select OpenAPI Access, and then click ok.
Click Copy to save the AccessKey pair (AccessKey ID and AccessKey Secret).
Step 2: Grant the RAM user the permissions to upload objects
Create a custom policy to grant the role permissions to upload objects.
In the left navigation bar, select
.Click Create Policy.
On the Create Policy page, click Edit Script, and then enter the following script in the policy editor to grant the role the permissions to upload objects to the exampledir directory in the examplebucket bucket. The following script provides an example on how to grant the role the permissions.
WarningThe following policy document is provided only for reference. 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 Authorize other users to access OSS resources by using RAM or STS.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "oss:PutObject", "Resource": "acs:oss:*:*:examplebucket/exampledir/*" } ] }
After you configure the policy, click Continue To Edit Basic Information.
In the Basic Information section, set the policy Name to RamTestPolicy, and then click OK.
Attach the custom policy to a RAM user.
In the left navigation bar, select
.On the Users page, find the RAM user.
Click Add Permissions in the Actions column corresponding to the RAM user.
On the Add Permissions page, click the Custom Policy tab, and then select the custom policy RamTestPolicy that you created.
Click OK.
Step 3: Use the AccessKey pair of the RAM user to upload objects to OSS
The following Java code provides an example on how to upload the local file examplefile.txt to the exampleobject.txt object in the exampledir directory of the examplebucket bucket.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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.
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();
}
}
}
}
For more information about examples on OSS SDKs for other programming languages, see the following topics:
FAQ
How do I view the AccessKey pair of a RAM user? Can I view the previous AccessKey Secret?
How do I troubleshoot the AccessDenied error that occurs when I use the AccessKey pair of a RAM user to upload objects?
How do I query the specific error type when an error occurs?
How do I resolve the NoSuchBucket error?
How do I resolve the The bucket you are attempting to access must be addressed using the specified endpoint. error?
References
After you upload objects to OSS, you can share the objects with third-party users for preview or download by using signed URLs. For more information, see Use a signed URL to download an object.