Security Token Service (STS) can grant a RAM user time-limited access to the specified resources in Object Storage Service (OSS) by issuing temporary access credentials to the RAM user. After the temporary access credentials expire, the RAM user cannot access the resources by using the temporary access credentials. STS helps improve flexibility and timeliness of access control.
Prerequisites
A bucket is created. For more information, see Create a bucket.
Step 1: Create a RAM user
Log on to the RAM console.
In the left-side navigation pane, choose Identities > Users.
On the Users page, click Create User.
Configure the Logon Name and Display Name parameters.
In the Access Mode section, select OpenAPI Access. Then, click OK.
Complete security verification as prompted.
Copy the AccessKey pair (AccessKey ID and AccessKey secret).
ImportantYou can obtain the AccessKey secret of a RAM user only when you create the RAM user. You must keep the AccessKey secret safely to prevent credential leaks.
Step 2: Grant the RAM user the permissions to call the AssumeRole operation
After you create the RAM user, grant the RAM user the permissions to call the AssumeRole operation of STS.
On the Users page, find the RAM user that you created and click Add Permissions in the Actions column.
In the Policy section of the Grant Permission panel, select the AliyunSTSAssumeRoleAccess policy.
NoteThe AliyunSTSAssumeRoleAccess policy allows a RAM user to call the AssumeRole operation. The permissions of the policy are independent of the permissions required for the RAM user to obtain temporary access credentials from STS and initiate requests to OSS.
Click Grant permissions.
Step 3: Create a RAM role
Create a RAM role to declare the permissions of the RAM role when the RAM role is assumed.
In the left-side navigation pane, choose Identities > Roles.
Click Create Role. In the Select Role Type step of the Create Role wizard, set Select Trusted Entity to Alibaba Cloud Account and click Next.
In the Configure Role step of the Create Role wizard, set RAM Role Name to RamOssTest and Select Trusted Alibaba Cloud Account to Current Alibaba Cloud Account.
Click OK. After the role is created, click Close.
On the Roles page, enter RamOssTest in the search box, click the search icon, and click RamOssTest in the search result.
Click Copy on the right side of the RamOssTest page to save the Alibaba Cloud Resource Name (ARN) of the role.
Step 4: Grant the RAM role the permissions to upload objects to OSS
Attach one or more policies to the RAM role to grant the RAM role the permissions to perform operations on OSS resources when the RAM role is assumed. For example, if you want a RAM user to assume this RAM role and only upload objects to a specific OSS bucket, you must attach a policy that grants write permissions to the RAM role.
Create a custom policy to grant the role the permissions to upload objects.
In the left-side navigation pane, choose Permissions > Policies.
On the Policies page, click Create Policy.
On the Create Policy page, click JSON. Enter the following script in the code editor to grant the RAM role the permissions to upload objects to the examplebucket bucket.
WarningThe following example is only for reference. You must configure fine-grained RAM policies based on your requirements to prevent granting excessive permissions to users. 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/*" ] } ] }
NoteThe Action element specifies the permissions that you want to grant to the RAM role. For example, if you specify oss:PutObject, the RAM user that assumes the RAM role can upload objects to the specified bucket by using various upload methods, such as simple upload, form upload, append upload, multipart upload, and resumable upload. For more information, see Action element in RAM policies for OSS.
Click Next to edit policy information.
In the Basic Information section, set Name to RamTestPolicy and click OK.
Attach the custom policy to the RamOssTest role.
In the left-side navigation pane, choose
.On the Roles page, find the RamOssTest role.
Click Grant Permission in the Actions column.
In the Grant Permission panel, select Custom Policy from the drop-down list in the Policy section and select the RamTestPolicy policy.
Click Grant permissions.
Step 5: Use the RAM user to assume the RAM role to obtain temporary access credentials
After you grant the RAM role the permissions to upload objects to OSS, the RAM user assumes the RAM role to obtain temporary access credentials. Temporary access credentials include a security token (SecurityToken), temporary AccessKey pair (AccessKey ID and AccessKey secret), and validity period (Expiration).
Use STS SDKs
You can use STS SDKs to obtain temporary access credentials.
The following sample code provides an example on how to use STS SDK for Java to obtain temporary access credentials that have the simple upload (oss:PutObject
) permission. For more information about how to use STS SDKs for other programming languages to obtain temporary access credentials, see STS SDK overview. For a list of STS endpoints, see Endpoints.
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
public class StsServiceSample {
public static void main(String[] args) {
// Specify the endpoint of STS. Example: sts.cn-hangzhou.aliyuncs.com. You can access STS over the Internet or a virtual private cloud (VPC).
String endpoint = "sts.cn-hangzhou.aliyuncs.com";
// Obtain the AccessKey ID and AccessKey secret of the RAM user generated in Step 1 from environment variables.
String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET");
// Obtain the ARN of the RAM role generated in Step 3 from environment variables.
String roleArn = System.getenv("OSS_STS_ROLE_ARN");
// Specify a custom role session name to distinguish different tokens. Example: SessionTest.
String roleSessionName = "yourRoleSessionName";
// Specify that the temporary access credentials have all permissions of the RAM role.
String policy = null;
// Specify the validity period of the temporary access credentials. Unit: seconds. The minimum validity period is 900 seconds. The maximum validity period is the same as the maximum session duration specified for the current role. The maximum session duration of the current role ranges from 3,600 seconds to 43,200 seconds. The default maximum session duration of the current role is 3,600 seconds.
// In large object upload or other time-consuming scenarios, we recommend that you set the validity period of temporary access credentials to a reasonable value to ensure that you do not need to repeatedly call the STS API operation to obtain temporary access credentials before the task is complete.
Long durationSeconds = 3600L;
try {
// Specify the region of STS. We recommend that you keep the default value. The default value is an empty string ("").
String regionId = "";
// Specify the endpoint. You can specify this parameter by using STS SDK for Java 3.12.0 or later.
DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
// Specify the endpoint. You can specify this parameter by using STS SDK for Java that is earlier than 3.12.0.
// DefaultProfile.addEndpoint("",regionId, "Sts", endpoint);
// Create a default profile.
IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
// Use the profile to create a client.
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
// You can specify this parameter by using STS SDK for Java 3.12.0 or later.
request.setSysMethod(MethodType.POST);
// You can specify this parameter by using STS SDK for Java that is earlier than 3.12.0.
// request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
request.setPolicy(policy);
request.setDurationSeconds(durationSeconds);
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("Expiration: " + response.getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
System.out.println("RequestId: " + response.getRequestId());
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
}
}
After temporary access credentials obtain permissions from a RAM role, you can further limit the permissions of the temporary access credentials. For example, if the temporary access credentials have the permissions to upload objects to the examplebucket bucket, you can refer to the following sample policy to specify that the access credentials can be used to upload data only to a specific directory in the bucket.
// The following policy specifies that the temporary access credentials can be used to upload objects only to the src directory of the examplebucket bucket.
// The final permissions granted to the temporary access credentials are the intersection of the role permissions that are specified in Step 4 and the permissions that are specified in the policy. This allows you to upload objects only to the src directory in the examplebucket bucket.
String policy = "{\n" +
" \"Version\": \"1\", \n" +
" \"Statement\": [\n" +
" {\n" +
" \"Action\": [\n" +
" \"oss:PutObject\"\n" +
" ], \n" +
" \"Resource\": [\n" +
" \"acs:oss:*:*:examplebucket/src/*\" \n" +
" ], \n" +
" \"Effect\": \"Allow\"\n" +
" }\n" +
" ]\n" +
"}";
Use RESTful APIs
You can call the AssumeRole operation of STS to obtain temporary access credentials.
Step 6: Use the temporary access credentials to upload objects to OSS
Before the validity period (Expiration) of the temporary access credentials ends, use the temporary access credentials to upload local files to OSS.
The expiration time of the temporary access credentials is in UTC, which is 8 hours earlier than the UTC+8 time zone that is used in China. For example, if the expiration time of temporary access credentials is 2024-04-18T11:33:40Z, the temporary access credentials expire on April 18, 2024 at 19:33:40 (UTC+8).
You can use temporary access credentials multiple times before they expire. For example, before temporary access credentials expire, you can use them to repeatedly call upload operations to upload multiple files or upload a package of the files.
The following sample code provides an example on how to upload the exampletest.txt file from the local path D:\\localpath
to the examplebucket bucket by using OSS SDK for Java 3.12.0. For more information about how to use temporary access credentials to upload data by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import java.io.File;
public class Demo {
public static void main(String[] args) throws ClientException {
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain the temporary AccessKey pair generated in Step 5 from environment variables.
String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET");
// Obtain the security token generated in Step 5 from environment variables.
String securityToken = System.getenv("OSS_SESSION_TOKEN");
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
// Upload a local file named exampletest.txt to examplebucket.
PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket", "exampletest.txt", new File("D:\\localpath\\exampletest.txt"));
// ObjectMetadata metadata = new ObjectMetadata();
// Specify the storage class of the uploaded object.
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// Specify the access control list (ACL) of the uploaded object.
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
try {
// Upload the local file.
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());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
FAQ
What do I do if the You are not authorized to do this action. You should be authorized by RAM. error message is returned?
What do I do if error message The Min/Max value of DurationSeconds is 15min/1hr. is returned?
What do I do if error message The security token you provided is invalid. is returned?
What do I do if error message The OSS Access Key Id you provided does not exist in our records. is returned?
What do I do if the AccessDenied: Anonymous access is forbidden for this operation. error message is returned?
What do I do if the NoSuchBucket error code is returned?
What do I do if the You have no right to access this object because of bucket acl. error message is returned when I use the temporary access credentials to access OSS resources?
What do I do if the Access denied by authorizer's policy. error message is returned when I use the temporary access credentials obtained from STS to perform operations on OSS resources?
What do I do if error message The bucket you are attempting to access must be addressed using the specified endpoint. is returned?
Can I obtain multiple sets of temporary access credentials at the same time?
What do I do if I receive a time format error?
What do I do if the 0003-0000301 error code is returned?
References
You can use temporary access credentials to upload data to OSS directly from your client and specify upload conditions, such as the file size, file types, and destination directories. For more information, see Direct client uploads.
You can use signed URLs to share objects that are uploaded by using temporary access credentials. For more information, see Share objects with object URLs.