You can use Security Token Service (STS) to generate temporary access credentials to authorize a RAM user to access your Object Storage Service (OSS) resources within a specific period of time. This way, you do not need to share your AccessKey pair. This ensures higher data security.
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 of the RAM user.
Step 2: Grant the RAM user the permissions to call the AssumeRole operation
After you create the RAM user, you must grant the RAM user the permissions to call the STS API operation by assuming a RAM role.
On the Users page, find the RAM user that you created and click Add Permissions in the Actions column.
In the Add Permissions panel, click the System Policy tab and select the AliyunSTSAssumeRoleAccess policy.
NoteThe RAM user is attached the AliyunSTSAssumeRoleAccess policy to call the AssumeRole operation of STS. The permissions of the AliyunSTSAssumeRoleAccess policy are independent of the permissions required to obtain temporary access credentials and initiate OSS requests by using temporary access credentials.
Click OK.
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 Create Role panel, set Select Trusted Entity to Alibaba Cloud Account and click Next.
In the Create Role panel, 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 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 upload only 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. Edit the script in the policy editor to grant the role the permissions to upload objects to the src and dest directories in the examplebucket bucket. The following code provides an example on how to grant the role the permissions.
WarningThe following example is for reference only. 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 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/src/*", "acs:oss:*:*:examplebucket/dest/*" ] } ] }
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 Identities > Roles.
On the Roles page, find the RamOssTest role.
Click Grant Permission in the Actions column of the RamOssTest role.
In the Grant Permission panel, click the Custom Policy tab and select the RamTestPolicy policy.
Click OK.
Step 5: Use the RAM user to assume the RAM role to obtain temporary access credentials
After you grant the RAM user the permissions to upload objects to OSS, the RAM user assumes the RAM role to obtain temporary access credentials. Temporary access credentials include security token (SecurityToken), temporary access key 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 that have the simple upload (oss:PutObject) permission, see STS SDK overview.
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";
// The following policy allows users to use only temporary access credentials to upload objects to the src directory of the examplebucket bucket.
// The permissions of the temporary access credentials are the intersection of the role permissions configured in Step 4 and the permissions specified by the RAM policy. Users can use the temporary access credentials to upload objects only to the src directory in the examplebucket bucket.
// If the policy is empty, the user is granted all permissions of the role.
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" +
"}";
// Specify the validity period of the temporary access credentials. Unit: seconds. The minimum value is 900. The maximum value is based on 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 destination task is complete.
Long durationSeconds = 3600L;
try {
// regionId specifies the region ID of the RAM user. For example, if the RAM user is located in the China (Hangzhou) region, set regionId to cn-hangzhou. You can also retain the default setting, which is an empty string ("").
String regionId = "";
// Add the endpoint. You can specify this parameter by using STS SDK for Java 3.12.0 or later.
DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
// Add 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());
}
}
}
For more information about STS endpoints, see Endpoints.
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 expires, use the temporary access credentials to upload an local file to OSS.
The following sample code provides an example on how to use OSS SDK for Java 3.12.0 to upload a local file named exampletest.txt from D:\\localpath
to the src directory in a bucket named examplebucket:
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. In this example, the endpoint of the China (Hangzhou) region is used. Example: 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 the exampletest.txt file to the src directory of the examplebucket bucket.
PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket", "src/exampletest.txt", new File("D:\\localpath\\exampletest.txt"));
// ObjectMetadata metadata = new ObjectMetadata();
// Specify the storage class when you upload the file.
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// Specify the access control list (ACL) when you upload the file.
// 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();
}
}
}
}
For more information about the storage class that you can specify for an object when you upload the object, see Overview. For more information about the ACL that you can specify for an object when you upload the object, see Object ACLs.
For more information about examples on OSS SDKs for other programming languages, see the following topics:
For more information about how to obtain the URL of an uploaded object, see Share objects with object URLs.
FAQ
What do I do if the The security token you provided is invalid. error message is returned?
What do I do if the The OSS Access Key Id you provided does not exist in our records. error message 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 from STS 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 from STS to perform operations on OSS resources?
What do I do if the The bucket you are attempting to access must be addressed using the specified endpoint. error message is returned?
Can I obtain multiple temporary access credentials at the same time?
What do I do if I receive an invalid time format error?
What do I do if the 0003-0000301 error code is returned?
References
You can upload data directly to OSS from clients by using temporary access credentials from STS. For more information, see Overview.