All Products
Search
Document Center

Simple Log Service:Use STS to enable cross-account access to Simple Log Service resources

Last Updated:Oct 28, 2024

You can use an Alibaba Cloud account (Alibaba Cloud Account A) to create a Resource Access Management (RAM) role, specify another Alibaba Cloud account (Alibaba Cloud Account B) to assume the RAM role, and grant the RAM role the specific permissions on Simple Log Service resources of Alibaba Cloud Account A. Then, you can grant the AssumeRole permission to a RAM user of Alibaba Cloud Account B. Then, you can use Alibaba Cloud Account B or the specified RAM user to call a Security Token Service (STS) API operation to obtain temporary security credentials. These credentials include the AccessKey ID, AccessKey secret, and security token. This way, you can use the RAM user to call Simple Log Service API operations and access Simple Log Service resources.

Background information

To isolate business data or outsourced projects, the user of Alibaba Cloud Account A wants to grant Alibaba Cloud Account B the specific permissions on Simple Log Service resources of Alibaba Cloud Account A. This way, the user of Alibaba Cloud Account B can manage and maintain the specified resources. The following permissions are granted:

  • Alibaba Cloud Account B is authorized to write data to Simple Log Service of Alibaba Cloud Account A. In addition, Alibaba Cloud Account B is authorized to use consumer groups to consume data from Simple Log Service of Alibaba Cloud Account A.

  • A RAM user of Alibaba Cloud Account B is authorized to write data to Simple Log Service of Alibaba Cloud Account A. In addition, the RAM user is authorized to use consumer groups to consume data from Simple Log Service of Alibaba Cloud Account A.

  • Alibaba Cloud Account B is authorized to call an STS API operation to obtain temporary security credentials and use the credentials to call Simple Log Service API operations. For more information, see What is STS?

Authorization process

  1. The user of Alibaba Cloud Account A creates a RAM role, specifies Alibaba Cloud Account B to assume this role, and grants Alibaba Cloud Account B the specified permissions on Simple Log Service resources of Alibaba Cloud Account A.

  2. The user of Alibaba Cloud Account B creates RAM User B1 and attaches the AliyunSTSAssumeRoleAccess system policy to RAM User B1. This policy allows RAM User B1 to call the AssumeRole API operation of STS.

  3. The user of RAM User B1 calls the AssumeRole API operation of STS. This way, RAM User B1 can initiate Simple Log Service API requests and manage the Simple Log Service resources of Alibaba Cloud Account A.

Step 1: The user of Alibaba Cloud Account A creates a RAM role for Alibaba Cloud Account B and grants permissions to Alibaba Cloud Account B

The user of Alibaba Cloud Account A creates a RAM role, specifies Alibaba Cloud Account B to assume the RAM role, and grants the RAM role the specific permissions on Simple Log Service resources of Alibaba Cloud Account A.

You can create a RAM role in the RAM console. For more information, see Create a RAM user and authorize the RAM user to access Simple Log Service. You can also call the CreateRole API operation of RAM to create a RAM role. For more information, see CreateRole. The following example describes how to create a RAM role in the console.

  1. Log on to the RAM console by using Alibaba Cloud Account A.

  2. Create a RAM role and specify Alibaba Cloud Account B to assume the RAM role.

    1. In the left-side navigation pane, choose Identities > Roles.

    2. On the Roles page, click Create Role.

    3. In the Select Role Type step of the Create Role wizard, select Alibaba Cloud Account as the trusted entity, and click Next.

    4. In the Configure Role step, configure the RAM Role Name and Note parameters. Select Other Alibaba Cloud Account for the Select Trusted Alibaba Cloud Account parameter, enter the ID of Alibaba Cloud Account B, and then click OK.

      Note

      To view the ID of an Alibaba Cloud account, move the pointer over the profile picture in the upper-right corner of the console.

      The following example shows the RAM role that was created in the preceding steps:

      {
        "Statement": [
          {
            "Action": "sts:AssumeRole",
            "Effect": "Allow",
            "Principal": {
              "RAM": [
                "acs:ram::<The ID of Alibaba Cloud Account B>:root"
              ]
            }
          }
        ],
        "Version": "1"
      }
  3. Create a policy.

    1. In the left-side navigation pane, choose Permissions > Policies.

    2. On the Policies page, click Create Policy.

    3. Click the JSON tab.

    4. On the JSON tab, replace the existing script in the code editor with one of the following scripts.

      The user of Alibaba Cloud Account A creates the policy to grant permissions to Alibaba Cloud Account B.

      The following policy grants the write permissions on Simple Log Service:

      {
        "Version": "1",
        "Statement": [
          {
            "Action": "log:PostLogStoreLogs",
            "Resource": "*",
            "Effect": "Allow"
          }
        ]
      }

      The following policy grants the permissions to use consumer groups to pull data from Simple Log Service:

      {
        "Version": "1",
        "Statement": [
          {
            "Action": [
               "log:GetCursorOrData",
               "log:CreateConsumerGroup",
               "log:ListConsumerGroup",
               "log:ConsumerGroupUpdateCheckPoint",
               "log:ConsumerGroupHeartBeat",
               "log:GetConsumerGroupCheckPoint",
               "log:UpdateConsumerGroup"
            ],
            "Resource": "*",
            "Effect": "Allow"
          }
        ]
      }

      The preceding policies grant permissions on all projects and Logstores of Alibaba Cloud Account A. If you want to grant permissions on a specific project and Logstore, include the following code in the Resource element of the policies:

      • To grant permissions on a project, use acs:log::{projectOwnerAliUid}:project/.

      • To grant permissions on a Logstore, use acs:log::{projectOwnerAliUid}:project/{projectName}/logstore/{logstoreName}/.

      For more information, see Simple Log Service resources that can be managed by RAM users.

    5. Click Next to edit policy information and configure the parameters. The following table describes the parameters.

      Parameter

      Description

      Name

      Enter a name for the policy.

      Description

      Enter remarks for the policy.

    6. Click OK.

  4. Use Alibaba Cloud Account A to grant permissions to the RAM role.

    1. In the left-side navigation pane, choose Identities > Roles.

    2. On the Roles page, find the RAM role that you created and click Grant Permission in the Actions column.

    3. In the Select Policy section of the Grant Permission page, click Custom Policy, click the policy that you created in 3, and then click OK.

    4. On the page that appears, click Complete.

Step 2: The user of Alibaba Cloud Account B creates RAM User B1 and grants permissions to RAM User B1

The user of Alibaba Cloud Account B creates RAM User B1 and attaches the AliyunSTSAssumeRoleAccess system policy to RAM User B1. This allows RAM User B1 to call the AssumeRole API operation of STS.

  1. Log on to the RAM console by using Alibaba Cloud Account B.

  2. In the left-side navigation pane, choose Identities > Users.

  3. On the Users page, click Create User.

  4. On the Create User page, configure the parameters and click OK. The following table describes the parameters.

    Parameter

    Description

    User Account Information

    Configure the Logon Name and Display Name parameters.

    Access Mode

    Select Console Access and OpenAPI Access.

  5. Return to the Users page. In the User Logon Name/Display Name column, find the RAM user that you created and click Add Permissions.

  6. On the Add Permissions page, configure the parameters. The Principal field is automatically filled. Select System Policy for the Select Policy field. In the Authorization Policy Name column, click the AliyunSTSAssumeRoleAccess policy and click OK.

  7. On the page that appears, click Complete.

Step 3: The user of RAM User B1 obtains temporary security credentials from STS to access Simple Log Service resources

  1. Call the AssumeRole API operation of STS to obtain the temporary AccessKey pair and security token. For more information, see AssumeRole.

    You can call this operation by using the following method:

    Call the operation by using STS SDK. For more information, see STS SDK overview.

  2. Call API operations of Simple Log Service. For more information about Simple Log Service SDK, see Overview of Simple Log Service SDK.

Sample code

For example, RAM User B1 uses STS to write data to a project of Alibaba Cloud Account A. The Java sample code is as follows:

Important

The STS API version used in this sample code is only available in the China (Hangzhou) region.

package com.aliyun.openservices.log.sample;

import java.util.Date;
import java.util.Vector;

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.PutLogsRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
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 StsSample {
	  // Currently, STS only supports "cn-hangzhou".
	  public static final String REGION_CN_HANGZHOU = "cn-hangzhou";
	  // Current STS API version
	  public static final String STS_API_VERSION = "2015-04-01";
	  static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret,
	                                       String roleArn, String roleSessionName, String policy,
	                                       ProtocolType protocolType) throws ClientException {
	    try {
	      // Construct Alibaba Cloud ACS Client to invoke OpenAPI.
	      IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
	      DefaultAcsClient client = new DefaultAcsClient(profile);
	      // Create AssumeRoleRequest object.
	      final AssumeRoleRequest request = new AssumeRoleRequest();
	      request.setVersion(STS_API_VERSION);
	      request.setMethod(MethodType.POST);
	      request.setProtocol(protocolType);
	      request.setRoleArn(roleArn);
	      request.setRoleSessionName(roleSessionName);
	      request.setPolicy(policy);
	      // Send request.
	      final AssumeRoleResponse response = client.getAcsResponse(request);
	      return response;
	    } catch (ClientException e) {
	      throw e;
	    }
	  }
	  public static void main(String[] args) {
	    // Only RAM users can invoke the AssumeRole API.
	    // The AccessKeys of Alibaba Cloud accounts cannot invoke the AssumeRole API.
	    // Create a RAM user in the RAM console (https://ram.console.aliyun.com), and create an AccessKey pair for the RAM user.
	    String accessKeyId = "<subaccountaccesskey>";
	    String accessKeySecret = "<subaccountaccesssecret>";
	    // AssumeRole API parameter: RoleArn, RoleSessionName, Policy, and DurationSeconds.
	    // RoleArn can be retrieved in the RAM console.
	    // https://ram.console.aliyun.com/#/role/detail/<specified rolename>/info
	    String roleArn = "<rolearn found in web console>";
	    // RoleSessionName is a temporary token, mainly used for auditing.
	    String roleSessionName = "bluemix-001";
	    String policy = "{\n" +
	            "    \"Version\": \"1\", \n" +
	            "    \"Statement\": [\n" +
	            "        {\n" +
	            "            \"Action\": \"log:PostLogStoreLogs\",\n" +
	            "            \"Resource\": \"*\",\n" +
	            "            \"Effect\": \"Allow\"\n" +
	            "        }\n" +
	            "    ]\n" +
	            "}";
	    System.out.println(policy);
	    // Only HTTPS is supported here.
	    ProtocolType protocolType = ProtocolType.HTTPS;
	    AssumeRoleResponse response = new AssumeRoleResponse();
	    try {
	      response = assumeRole(accessKeyId, accessKeySecret,
	              roleArn, roleSessionName, policy, protocolType);
	      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());
	    } catch (ClientException e) {
	      System.out.println("Failed to get a token.");
	      System.out.println("Error code: " + e.getErrCode());
	      System.out.println("Error message: " + e.getErrMsg());
	    }
	    
	    // Simple Log Service parameters.
	    // Simple Log Service endpoint document: https://www.alibabacloud.com/help/en/sls/developer-reference/api-sls-2020-12-30-endpoint
	    String logServiceEndpoint = "cn-hangzhou.log.aliyuncs.com";
	    // Project region is cn-hangzhou
	    String project = "<log service project name>";
	    String logstore = "<log service logstore name>";
	    
	    // Construct Simple Log Service client object.
	    Client client = new Client(logServiceEndpoint, 
	    		response.getCredentials().getAccessKeyId(), 
	    		response.getCredentials().getAccessKeySecret());
	    // Note: The AccessKey and security token will expire in 1 hour, 
	    // so you must invoke the AssumeRole API when they expire.
	    client.SetSecurityToken(response.getCredentials().getSecurityToken());
	    Vector<LogItem> logGroup = new Vector<LogItem>();
	    LogItem logItem = new LogItem((int) (new Date().getTime() / 1000));
	    logItem.PushBack("StsSample", "Send Data");
	    logGroup.add(logItem);
	    
	    PutLogsRequest req2 = new PutLogsRequest(project, logstore, "", "", logGroup);
	    try {
	    	client.PutLogs(req2);
	    } catch (LogException e) {
			System.out.println("Failed to send data.");
			System.out.println("Error code: " + e.GetErrorCode());
			System.out.println("Error message: " + e.GetErrorMessage());
	    }
	  }
}