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
Sign in to the RAM console using your Alibaba Cloud account or as a RAM user with administrative permissions (a user to which the
AliyunRAMFullAccesspolicy is attached).In the left-side navigation pane, choose .
On the Users page, click Create User.
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
, then enter a tag key and tag value to categorize and manage users.
NoteClick Add User to create multiple RAM users in bulk.
In the Access Mode section, select an access mode based on the user type.
ImportantAs 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.
Set Logon Password: Auto-generate or set a custom password. Custom passwords must meet the configured complexity requirements. Set a password policy for RAM users.
Password Reset: Specify whether the user must reset the password at next sign-in.
Enable MFA: MFA is required for all users by default. To change this setting, see Manage RAM user security settings. Users must bind an MFA device at first sign-in. Bind an MFA device.
Programmatic access
Select Permanent AccessKey.
The system automatically creates an AccessKey ID and AccessKey secret for the RAM user.
ImportantThe 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
-
Create a custom policy for uploading objects.
-
In the left-side navigation pane, choose .
-
Click Create Policy.
-
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.
WarningThe 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/*" } ] } -
After the policy is configured, click Continue to Edit Basic Information.
-
In the Basic Information section, set the policy Name to RamTestPolicy, and then click OK.
-
-
Grant the custom policy to the RAM user.
-
In the left-side navigation pane, choose .
-
On the Users page, find the target RAM user.
-
Click Add Permissions on the right side of the RAM user.
-
On the Add Permissions page, click the Custom Policy tab, and select the custom policy you created: RamTestPolicy.
-
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();
}
}
}
}
For SDK examples in other languages, see:
FAQ
How do I view the AccessKey pair of a RAM user? Can I view the old AccessKey Secret?
How do I troubleshoot the AccessDenied error when uploading objects by using the AccessKey pair of a RAM user?
How do I query specific error types when errors occur?
How do I handle the NoSuchBucket error?
How do I handle the The bucket you are attempting to access must be addressed using the specified endpoint. error?
Related Documentation
-
After an object is uploaded to OSS, you can share the object with third-party users for preview or download by using a signed URL. For more information, see Using presigned URLs to download or preview files.