All Products
Search
Document Center

Simple Log Service:Extend the validity periods of URLs to embedded console pages

Last Updated:Aug 13, 2024

Simple Log Service allows you to share the pages of query and analysis results and dashboard pages of the Simple Log Service console with other users and embed the console pages into third-party systems. This way, other users can view your logs in password-free and logon-free mode. The URLs of the shared pages are referred to as password-free and logon-free URLs. You can call the CreateTicket operation to obtain a ticket and generate a password-free and logon-free URL based on the ticket and the URL of the console page that you want to share. A ticket returned by the CreateTicket operation is valid for a short period of time. As a result, the validity period of the password-free and logon-free URL that is generated based on the ticket is also short. If you want to extend the validity period, you can call the RefreshToken operation. This topic describes how to extend the validity periods of password-free and logon-free URLs.

How it works

image

Prerequisites

A password-free and logon-free URL is generated. For more information, see Embed console pages and share log data (new version).

Procedure

Step 1: Grant the required permissions to a RAM user

If you use an Alibaba Cloud account, you can skip this step and go to Step 2.

  1. Log on to the Resource Access Management (RAM) console by using the RAM user that generates the password-free and logon-free URL.

  2. Grant the permissions to call the RefreshToken operation to the RAM user. For more information, see Grant permissions to a RAM user and Create custom policies.

    {
        "Version": "1",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": "log:RefreshToken",
                "Resource": "acs:log:*:*:ticket/*"
            }
        ]
    }

Step 2: Add a parameter to the password-free and logon-free URL

Concatenate the password-free and logon-free URL and the supportRefreshToken parameter. The supportRefreshToken parameter specifies whether the third-party server supports the RefreshToken operation. Set the supportRefreshToken parameter to true to extend the validity period of the password-free and logon-free URL.

https://sls.console.aliyun.com/lognext/project/<Project name>/dashboard/<Dashboard ID>?sls_ticket=eyJ***************.eyJ******************.KUT****************&supportRefreshToken=true&isShare=true&hideTopbar=true&hideSidebar=true&ignoreTabLocalStorage=true

Step 3: Monitor events on the client side

The third-party client monitors the message event and sends the latest ticket to the related iFrame.

window.addEventListener('message', async (e) => {
  if (e?.data?.type === 'refreshToken') {
    const accessToken = await callApi()
    document.querySelector('#myIframe').contentWindow.postMessage(
      {
        // The value is fixed as applyAccessToken.
        type: 'applyAccessToken',
        // The ticket that is obtained by calling the callApi method.
        accessToken,
        // The ticket that is obtained by calling the CreateTicket operation.
        ticket: e.data.ticket,
      },
      '*'
    )
  }
})
Important
  • The callApi() method is a custom method. The third-party client uses the callApi() method to call the API of the third-party server, which then calls the RefreshToken operation to obtain a ticket. For more information about how to integrate the RefreshToken operation into your business code, see Sample code.

  • When you call the RefreshToken operation to obtain a ticket, you must use the Simple Log Service endpoint for the China (Shanghai) or Singapore region. After you obtain the ticket, you can use the ticket regardless of the region.

  • The RefreshToken operation requires the following input parameters: ticket and accessTokenExpirationTime. ticket specifies the ticket that is generated by calling the CreateTicket operation. accessTokenExpirationTime specifies the validity period of the ticket that is generated by the calling the RefreshToken operation. Unit: seconds. Maximum value: 86400. Default value: 86400, which is equivalent to one day. The validity period of a ticket can be extended to 30 days at most. The RefreshToken operation is called once a day before the ticket expires.

Sample code

The following sample code provides an example on how to use the RefreshToken operation:

Java

  1. Add Maven dependencies.

    Open the pom.xml file in the root directory of your Java project and add the following code:

        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>sls20201230</artifactId>
          <version>5.2.1</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-openapi</artifactId>
          <version>0.3.2</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-console</artifactId>
          <version>0.0.1</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-util</artifactId>
          <version>0.2.21</version>
        </dependency>
  2. Generate a ticket.

    // This file is auto-generated, don't edit it. Thanks.
    package com.aliyun.sample;
    
    import com.aliyun.sls20201230.Client;
    import com.aliyun.tea.*;
    
    public class Sample {
    
        /**
         * Use your AccessKey ID and AccessKey secret to initialize a client.
         * @return Client
         * @throws Exception
         */
        public static Client createClient() throws Exception {
            // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. The following sample code is provided only for reference. 
            // We recommend that you use Security Token Service (STS) tokens, which provide higher security. 
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // For more information about endpoints, see https://api.aliyun.com/product/Sls.
            config.endpoint = "cn-shanghai.log.aliyuncs.com";
            return new Client(config);
        }
    
        public static void main(String[] args_) throws Exception {
            java.util.List<String> args = java.util.Arrays.asList(args_);
            com.aliyun.sls20201230.Client client = Sample.createClient();
            com.aliyun.sls20201230.models.RefreshTokenRequest refreshTokenRequest = new com.aliyun.sls20201230.models.RefreshTokenRequest()
                    .setTicket("eyJ***************.eyJ******************.KUT****************")
                    .setAccessTokenExpirationTime(60L);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            java.util.Map<String, String> headers = new java.util.HashMap<>();
            try {
                com.aliyun.sls20201230.models.RefreshTokenResponse resp = client.refreshTokenWithOptions(refreshTokenRequest, headers, runtime);
                com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(resp));
            } catch (TeaException error) {
                // Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed in the console. 
                // Display an error message.
                System.out.println(error.getMessage());
                // Display information for troubleshooting.
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            } catch (Exception _error) {
                TeaException error = new TeaException(_error.getMessage(), _error);
                // Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed in the console. 
                // Display an error message.
                System.out.println(error.getMessage());
                // Display information for troubleshooting.
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            }        
        }
    }
    

Python

# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys

from typing import List

from alibabacloud_sls20201230.client import Client as Sls20201230Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_sls20201230 import models as sls_20201230_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Sls20201230Client:
        """
        Use your AccessKey ID and AccessKey secret to initialize a client.
        @return: Client
        @throws Exception
        """
        # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. The following sample code is provided only for reference. 
        # We recommend that you use STS tokens, which provide higher security. 
        config = open_api_models.Config(
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
            access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
            access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        )
        # For more information about endpoints, see https://api.aliyun.com/product/Sls.
        config.endpoint = f'cn-shanghai.log.aliyuncs.com'
        return Sls20201230Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        refresh_token_request = sls_20201230_models.RefreshTokenRequest(
            ticket='eyJ***************.eyJ******************.KUT****************',
            access_token_expiration_time=60
        )
        runtime = util_models.RuntimeOptions()
        headers = {}
        try:
            # If you copy and run the sample code, add code to display the API call results.
            client.refresh_token_with_options(refresh_token_request, headers, runtime)
        except Exception as error:
            # Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed in the console. 
            # Display an error message.
            print(error.message)
            # Display information for troubleshooting.
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        refresh_token_request = sls_20201230_models.RefreshTokenRequest(
            ticket='eyJ***************.eyJ******************.KUT****************',
            access_token_expiration_time=60
        )
        runtime = util_models.RuntimeOptions()
        headers = {}
        try:
            # If you copy and run the sample code, add code to display the API call results.
            await client.refresh_token_with_options_async(refresh_token_request, headers, runtime)
        except Exception as error:
            # Handle exceptions with caution in actual business scenarios and never ignore exceptions in your project. In this example, error messages are displayed in the console. 
            # Display an error message.
            print(error.message)
            # Display information for troubleshooting.
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)


if __name__ == '__main__':
    Sample.main(sys.argv[1:])