Ao compartilhar ou incorporar páginas do console do Simple Log Service por meio de URLs sem senha e sem login, os tickets associados a essas URLs expiram rapidamente. Para prolongar o período de validade dessas URLs, chame a operação RefreshToken.
Como funciona
Pré-requisitos
Gere uma URL sem senha e sem login. Para mais informações, consulte Incorporar e compartilhar páginas do console.
Procedimento
Etapa 1: Conceder as permissões necessárias a um usuário RAM
Se você usa uma conta Alibaba Cloud, pule esta etapa e vá para a Etapa 2.
Faça login no console do Resource Access Management (RAM) com o usuário RAM que gera a URL sem senha e sem login.
-
Conceda ao usuário RAM as permissões para chamar a operação RefreshToken. Para mais informações, consulte Gerenciar permissões de usuários RAM e Criar uma política personalizada.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "log:RefreshToken", "Resource": "acs:log:*:*:ticket/*" } ] }
Etapa 2: Adicionar um parâmetro à URL sem senha e sem login
Anexe o parâmetro supportRefreshToken à URL sem senha e sem login. Esse parâmetro indica se o servidor de terceiros oferece suporte à operação RefreshToken. Defina o parâmetro supportRefreshToken como true para ativar a atualização de token da URL.
https://sls.console.alibabacloud.com/lognext/project/<Project name>/dashboard/<Dashboard ID>?sls_ticket=eyJ***************.eyJ******************.KUT****************&supportRefreshToken=true&isShare=true&hideTopbar=true&hideSidebar=true&ignoreTabLocalStorage=true
Etapa 3: Monitorar eventos no lado do cliente
O cliente de terceiros monitora o evento message e envia o ticket mais recente para o iFrame correspondente.
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,
},
'*'
)
}
})
O método
callApi()é personalizado. O cliente de terceiros o utiliza para chamar a API do servidor de terceiros, que então invoca a operação RefreshToken para obter umticket. Para mais detalhes sobre como integrar a operação RefreshToken ao seu código de negócios, consulte Código de exemplo.Ao chamar a operação RefreshToken para obter um
ticket, use o endpoint do Simple Log Service da região China (Shanghai) ou Singapore. Após a obtenção, oticketfunciona em todas as regiões.A operação RefreshToken exige dois parâmetros de entrada: ticket e accessTokenExpirationTime. O
ticketrefere-se ao ticket gerado pela operação CreateTicket. Já oaccessTokenExpirationTimedefine o período de validade do novo ticket, em segundos. Valor máximo: 86400. Valor padrão: 86400 (um dia). É possível estender um ticket por até 30 dias. Chame a operação RefreshToken uma vez por dia antes que o ticket expire.
Código de exemplo
Os exemplos a seguir demonstram como chamar a operação RefreshToken:
Java
-
Adicione as dependências do Maven.
Abra o arquivo pom.xml no diretório raiz do seu projeto Java e adicione o seguinte código:
<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> -
Gere um
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:])