The JS client needs the data from the STS

Help.aliyun.com/document_de…

  • regionalregion(If hangzhou, fill inoss-cn-hangzhou)
  • Temporary access certificateIncluding:Temporary access key(accessKeyIdandaccessKeySecret) andSecurity token(stsToken)
  • The name of the Bucket(bucket)

For details about how to set up the STS service, see the Development guide for accessing OSS using STS Temporary Access Credentials. You can obtain temporary access credentials by calling the AssumeRole interface for the STS service or using the STS SDK for each language.

So, let’s use the STS temporary access credentials to access the OSS link and see how to set up the STS service.

Use STS temporary access credentials to access OSS

Applicable scenario

Assume that you are a mobile App developer who wants to use ali Cloud OSS service to store App end-user data and ensure data isolation between each App user. At this point, you can access OSS directly using the STS authorized user.

The process for accessing OSS directly using the STS authorized user is as follows:

  1. App user login. App users have nothing to do with cloud accounts. They are the end users of App, and the App server supports App users to log in. For each valid App user, the App server is required to define the minimum access rights for each App user.
  2. The App server requests the STS service to obtain a SecurityToken. Before invoking STS, the App server needs to determine the minimum access rights for App users (customized authorization policies with RAM Policy) and the expiration time of credentials. The role is then assumed to be the assumption to obtain a SecurityToken representing the role’s identity.
  3. The STS returns a temporary access certificate to the App server, including a SecurityToken, temporary access key (AccessKeyId and AccessKeySecret), and expiration time.
  4. The App server returns temporary access credentials to the App client, which can cache the credentials. When the credentials become invalid, the App client needs to apply for a new temporary access certificate from the App server. For example, if the temporary access certificate is valid for one hour, the App client can request the App server to update the temporary access certificate every 30 minutes.
  5. App clients request the OSS API using locally cached temporary access credentials. After OSS receives an access request, the STS service verifies the access credentials and responds correctly to the user’s request.

Step 1: Create a RAM user

  1. Log in to the RAM console.
  2. In the left navigation bar, click Users under the People Management menu.
  3. Click Create user.
  4. Enter a login name and display name.
  5. Under the Access Mode area, select Programmatic access, and then click OK.
  6. Click copy to save the AccessKey (AccessKey ID and AccessKey Secret).

Step 2: Grant the permission for the RAM user to request the Sumerole

  1. Click Add Permission corresponding to the created RAM user.
  2. In the add permissions page, select the AliyunSTSAssumeRoleAccess permissions.
  3. Click OK.

Step 3: Create a role to get temporary access credentials

  1. In the left navigation bar, click RAM Role Management.
  2. Click Create RAM role, select the trusted entity type as Ali Cloud account, and click Next.
  3. On the page for creating RAM Role, set RAM role name to RamOssTest and select the cloud account as the current cloud account.
  4. Click Finish. After the role is created, click Close.
  5. On the RAM Role Management page, enter the role name RamOssTest in the search box.
  6. Click Copy to save the ARN of the role.

Step 4: Grant the permission to upload files to the role

  1. In the navigation tree on the left, click Permission Policy Management.
  2. Click to create a permission policy.
  3. On the page for creating a user-defined permission policy, set the policy name, select script configuration for configuration mode, and grant the role permission to upload files to directory ExampleDir under target storage space ExampleBucket.

Warning: The following examples are for reference only. You need to configure fine-grained authorization policies based on site requirements to prevent risks of excessive permissions. For more granular authorization policy configuration details, see Authorization to Other Users via RAM or STS Service.

{
    "Version": "1"."Statement": [{"Effect": "Allow"."Action": [
             "oss:PutObject"]."Resource": [
             "acs:oss:*:*:examplebucket/exampledir"."acs:oss:*:*:examplebucket/exampledir/*"]]}}Copy the code
  1. Click OK.

Step 5: Obtain temporary access credentials

You can obtain temporary access credentials by calling the STS service interface Sumerole or using the STS SDK for each language.

Take the Java SDK as an example:

package com.aliyun.sts.sample;
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.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
public class StsServiceSample {
    public static void main(String[] args) { 
        // STs.cn-hangzhou.aliyuncs.com.
        String endpoint = "<sts-endpoint>";
        // Enter AccessKey ID and AccessKey Secret generated in Step 1.
        String AccessKeyId = "<yourAccessKeyId>""; String accessKeySecret = "<yourAccessKeySecret>"; // Enter role ARN obtained in Step 3. String roleArn = "<yourRoleArn>"; // Customize the role session name to distinguish different tokens, for example, SessionTest. String roleSessionName = "<yourRoleSessionName>"; // The following Policy restricts the use of temporary access credentials to upload files to the target storage space exampleBucket. // The temporary access certificate finally obtains the permission of the role set in Step 4 and the permission set in the Policy. That is, only files can be uploaded to the exampleDir directory under target storage space ExampleBucket. String policy = "{\n"+"    \"Version\": \"1\", \n" +
                " \"Statement\": [\n" +
                " {\n" +
                " \"Action\": [\n" +
                " \"oss:PutObject\"\n" +
                " ], \n" +
                " \"Resource\": [\n" +
                " \"acs:oss:*:*:examplebucket/*\" \n" +
                " ], \n" +
                " \"Effect\": \"Allow\"\n" +
                " }\n" +
                " ]\n" +
                "}";
        try {
            // Add an endpoint.
            DefaultProfile.addEndpoint("".""."Sts", endpoint);
            // Construct a default profile.
            IClientProfile profile = DefaultProfile.getProfile("", AccessKeyId, accessKeySecret);
            // Construct the client.
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); // If policy is empty, the user has all permissions for the role.
            request.setDurationSeconds(3600L); // Set the validity of temporary access credentials to 3600 seconds.
            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()); }}}Copy the code

instructions

  • The unit of valid temporary access credentials is second. The minimum value is 900, and the maximum value is based on the maximum session time set by the current role. For details, see Setting the Maximum Session Time of a Role.
  • About the role session nameroleSessionNameSee naming conventions for theAssumeRole.

Step 6: Upload files to OSS using temporary access credentials

Using the Java SDK as an example, the example code for uploading the exampletest. TXT file in the D:\\ localPath directory to the exampleDir directory in the examplebucket storage space is as follows:

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.File;

public class upload {
    public static void main(String[] args) {

// Enter the temporary access keys obtained in Step 5 (AccessKey ID and AccessKey Secret).
String AccessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
// Enter the SecurityToken obtained in Step 5.
String securityToken = "<yourSecurityToken>";

// Create an OSSClient instance.
OSSClient ossClient = new OSSClient(endpoint, AccessKeyId, accessKeySecret, securityToken);
// Upload local file exampletest. TXT to directory exampledir under target storage space ExampleBucket.
PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket"."exampledir/exampletest.txt".new File("D:\\localpath\\exampletest.txt"));

// If you need to set the storage type and access permission when uploading, refer to the following example code.
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

// Upload the file.
ossClient.putObject(putObjectRequest);

// Close OSSClient.ossClient.shutdown(); }}Copy the code

See SDK examples for more languages:

  • Java SDK
  • Python SDK
  • Go SDK
  • C++ SDK
  • PHP SDK
  • C SDK
  • .NET SDK
  • Node.js SDK
  • Browser.js SDK
  • Android SDK
  • iOS SDK

For details about how to obtain the URL after Object is uploaded, see How Do I Obtain the URL After Object Is Uploaded? .

Best practices for direct transfer in mobile applications

The application server requests an AssumeRole from OSS and returns an STS credential to the mobile. Then, the mobile terminal will complete the upload task according to this credential.