步骤 2:获取附带身份验证代码的 URL - Amazon QuickSight

步骤 2:获取附带身份验证代码的 URL

重要

Amazon QuickSight 推出了用于嵌入分析的新 API:GenerateEmbedUrlForAnonymousUserGenerateEmbedUrlForRegisteredUser

您仍然可以使用 GetDashboardEmbedUrlGetSessionEmbedUrl API 来嵌入控制面板和 QuickSight 控制台,但其不包含最新的嵌入功能。有关最新的嵌入体验,请参阅 将 QuickSight 分析嵌入到您的应用程序中

 适用于:企业版 
   目标受众:Amazon QuickSight 开发人员 

在下节中,您可以了解如何代表匿名访问者进行身份验证,并获取应用程序服务器上的可嵌入控制面板 URL。

用户访问您的应用程序时,该应用程序代表用户代入 IAM 角色。然后,其会将用户添加到 QuickSight 中(如果该用户尚不存在)。接下来,其会将标识符作为唯一角色会话 ID 进行传递。

以下示例展示了代表用户执行 IAM 身份验证。将标识符作为唯一角色会话 ID 进行传递。此代码在您的应用程序服务器上运行。

Java
import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.quicksight.AmazonQuickSight; import com.amazonaws.services.quicksight.AmazonQuickSightClientBuilder; import com.amazonaws.services.quicksight.model.GetDashboardEmbedUrlRequest; import com.amazonaws.services.quicksight.model.GetDashboardEmbedUrlResult; /** * Class to call QuickSight AWS SDK to get url for dashboard embedding. */ public class GetQuicksightEmbedUrlNoAuth { private static String ANONYMOUS = "ANONYMOUS"; private final AmazonQuickSight quickSightClient; public GetQuicksightEmbedUrlNoAuth() { this.quickSightClient = AmazonQuickSightClientBuilder .standard() .withRegion(Regions.US_EAST_1.getName()) .withCredentials(new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { // provide actual IAM access key and secret key here return new BasicAWSCredentials("access-key", "secret-key"); } @Override public void refresh() {} } ) .build(); } public String getQuicksightEmbedUrl( final String accountId, // YOUR AWS ACCOUNT ID final String dashboardId, // YOUR DASHBOARD ID TO EMBED final String addtionalDashboardIds, // ADDITIONAL DASHBOARD-1 ADDITIONAL DASHBOARD-2 final boolean resetDisabled, // OPTIONAL PARAMETER TO ENABLE DISABLE RESET BUTTON IN EMBEDDED DASHBAORD final boolean undoRedoDisabled // OPTIONAL PARAMETER TO ENABLE DISABLE UNDO REDO BUTTONS IN EMBEDDED DASHBAORD ) throws Exception { GetDashboardEmbedUrlRequest getDashboardEmbedUrlRequest = new GetDashboardEmbedUrlRequest() .withDashboardId(dashboardId) .withAdditionalDashboardIds(addtionalDashboardIds) .withAwsAccountId(accountId) .withNamespace("default") // Anonymous embedding requires specifying a valid namespace for which you want the embedding url .withIdentityType(ANONYMOUS) .withResetDisabled(resetDisabled) .withUndoRedoDisabled(undoRedoDisabled); GetDashboardEmbedUrlResult dashboardEmbedUrl = quickSightClient.getDashboardEmbedUrl(getDashboardEmbedUrlRequest); return dashboardEmbedUrl.getEmbedUrl(); } }
JavaScript
global.fetch = require('node-fetch'); const AWS = require('aws-sdk'); function getDashboardEmbedURL( accountId, // YOUR AWS ACCOUNT ID dashboardId, // YOUR DASHBOARD ID TO EMBED additionalDashboardIds, // ADDITIONAL DASHBOARD-1 ADDITIONAL DASHBOARD-2 quicksightNamespace, // VALID NAMESPACE WHERE YOU WANT TO DO NOAUTH EMBEDDING resetDisabled, // OPTIONAL PARAMETER TO ENABLE DISABLE RESET BUTTON IN EMBEDDED DASHBAORD undoRedoDisabled, // OPTIONAL PARAMETER TO ENABLE DISABLE UNDO REDO BUTTONS IN EMBEDDED DASHBAORD getEmbedUrlCallback, // GETEMBEDURL SUCCESS CALLBACK METHOD errorCallback // GETEMBEDURL ERROR CALLBACK METHOD ) { const getDashboardParams = { AwsAccountId: accountId, DashboardId: dashboardId, AdditionalDashboardIds: additionalDashboardIds, Namespace: quicksightNamespace, IdentityType: 'ANONYMOUS', ResetDisabled: resetDisabled, SessionLifetimeInMinutes: 600, UndoRedoDisabled: undoRedoDisabled }; const quicksightGetDashboard = new AWS.QuickSight({ region: process.env.AWS_REGION, }); quicksightGetDashboard.getDashboardEmbedUrl(getDashboardParams, function(err, data) { if (err) { console.log(err, err.stack); errorCallback(err); } else { const result = { "statusCode": 200, "headers": { "Access-Control-Allow-Origin": "*", // USE YOUR WEBSITE DOMAIN TO SECURE ACCESS TO GETEMBEDURL API "Access-Control-Allow-Headers": "Content-Type" }, "body": JSON.stringify(data), "isBase64Encoded": false } getEmbedUrlCallback(result); } }); }
Python3
import json import boto3 from botocore.exceptions import ClientError import time # Create QuickSight and STS clients qs = boto3.client('quicksight',region_name='us-east-1') sts = boto3.client('sts') # Function to generate embedded URL # accountId: YOUR AWS ACCOUNT ID # dashboardId: YOUR DASHBOARD ID TO EMBED # additionalDashboardIds: ADDITIONAL DASHBOARD-1 ADDITIONAL DASHBOARD-2 WITHOUT COMMAS # quicksightNamespace: VALID NAMESPACE WHERE YOU WANT TO DO NOAUTH EMBEDDING # resetDisabled: PARAMETER TO ENABLE DISABLE RESET BUTTON IN EMBEDDED DASHBAORD # undoRedoDisabled: OPTIONAL PARAMETER TO ENABLE DISABLE UNDO REDO BUTTONS IN EMBEDDED DASHBAORD def getDashboardURL(accountId, dashboardId, quicksightNamespace, resetDisabled, undoRedoDisabled): try: response = qs.get_dashboard_embed_url( AwsAccountId = accountId, DashboardId = dashboardId, AdditionalDashboardIds = additionalDashboardIds, Namespace = quicksightNamespace, IdentityType = 'ANONYMOUS', SessionLifetimeInMinutes = 600, UndoRedoDisabled = undoRedoDisabled, ResetDisabled = resetDisabled ) return { 'statusCode': 200, 'headers': {"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type"}, 'body': json.dumps(response), 'isBase64Encoded': bool('false') } except ClientError as e: print(e) return "Error generating embeddedURL: " + str(e)
Node.js

以下示例显示了可以在应用程序服务器上使用以获取嵌入式控制面板 URL 的 JavaScript (Node.js)。您可以在网站或应用程序中使用该 URL 以显示控制面板。

const AWS = require('aws-sdk'); const https = require('https'); var quicksight = new AWS.Service({ apiConfig: require('./quicksight-2018-04-01.min.json'), region: 'us-east-1', }); quicksight.getDashboardEmbedUrl({ 'AwsAccountId': '111122223333', 'DashboardId': 'dashboard-id', 'AdditionalDashboardIds': 'added-dashboard-id-1 added-dashboard-id-2 added-dashboard-id-3' 'Namespace' : 'default', 'IdentityType': 'ANONYMOUS', 'SessionLifetimeInMinutes': 100, 'UndoRedoDisabled': false, 'ResetDisabled': true }, function(err, data) { console.log('Errors: '); console.log(err); console.log('Response: '); console.log(data); });
//The URL returned is over 900 characters. For this example, we've shortened the string for //readability and added ellipsis to indicate that it's incomplete. { Status: 200, EmbedUrl: 'https://dashboards.example.com/embed/620bef10822743fab329fb3751187d2d… RequestId: '7bee030e-f191-45c4-97fe-d9faf0e03713' }
.NET/C#

以下示例显示了可以在应用程序服务器上使用以获取嵌入式控制面板 URL 的 .NET/C# 代码。您可以在网站或应用程序中使用该 URL 以显示控制面板。

var client = new AmazonQuickSightClient( AccessKey, SecretAccessKey, sessionToken, Amazon.RegionEndpoint.USEast1); try { Console.WriteLine( client.GetDashboardEmbedUrlAsync(new GetDashboardEmbedUrlRequest { AwsAccountId = “111122223333”, DashboardId = "dashboard-id", AdditionalDashboardIds = "added-dashboard-id-1 added-dashboard-id-2 added-dashboard-id-3", Namespace = default, IdentityType = IdentityType.ANONYMOUS, SessionLifetimeInMinutes = 600, UndoRedoDisabled = false, ResetDisabled = true }).Result.EmbedUrl ); } catch (Exception ex) { Console.WriteLine(ex.Message); }
AWS CLI

要担任该角色,请选择以下 AWS Security Token Service (AWS STS) API 操作之一:

  • AssumeRole – 在使用 IAM 身份代入角色时使用该操作。

  • AssumeRoleWithWebIdentity – 在使用 Web 身份提供者对用户进行身份验证时使用该操作。

  • AssumeRoleWithSaml – 在使用安全断言标记语言(SAML)对用户进行身份验证时使用此操作。

以下示例显示了用于设置 IAM 角色的 CLI 命令。该角色需要为 quicksight:GetDashboardEmbedURL 启用权限。

aws sts assume-role \ --role-arn "arn:aws:iam::11112222333:role/QuickSightEmbeddingAnonymousPolicy" \ --role-session-name anonymous caller

assume-role 操作返回三个输出参数:访问密钥、私有密钥和会话令牌。

注意

如果在调用 AssumeRole 操作时遇到 ExpiredToken 错误,可能是因为之前的 SESSION TOKEN 仍在环境变量中。通过设置以下变量可以解决这一问题:

  • AWS_ACCESS_KEY_ID

  • AWS_SECRET_ACCESS_KEY

  • AWS_SESSION_TOKEN

以下示例说明了如何在 CLI 中设置这三个参数。如果您使用 Microsoft Windows 计算机,请使用 set 而不是 export

export AWS_ACCESS_KEY_ID = "access_key_from_assume_role" export AWS_SECRET_ACCESS_KEY = "secret_key_from_assume_role" export AWS_SESSION_TOKEN = "session_token_from_assume_role"

如果运行这些命令,则会将访问您的网站的用户的角色会话 ID 设置为 embedding_quicksight_dashboard_role/QuickSightEmbeddingAnonymousPolicy。角色会话 ID 由 role-arn 中的角色名称和 role-session-name 值组成。每个用户使用唯一的角色会话 ID 可以确保为每个访问用户设置相应的权限。其还能让每个会话保持独立性和独特性。如果您使用一组 Web 服务器(例如用于负载平衡),并且会话重新连接到其他服务器,则会开始新的会话。

要获取控制面板的签名 URL,请从应用程序服务器中调用 get-dashboard-embed-url。这会返回可嵌入的控制面板 URL。以下示例演示了如何使用服务器端调用为匿名访问您 Web 门户或应用程序的用户获取嵌入式控制面板的 URL。

aws quicksight get-dashboard-embed-url \ --aws-account-id 111122223333 \ --dashboard-id dashboard-id \ --additional-dashboard-ids added-dashboard-id-1 added-dashboard-id-2 added-dashboard-id-3 --namespace default-or-something-else \ --identity-type ANONYMOUS \ --session-lifetime-in-minutes 30 \ --undo-redo-disabled true \ --reset-disabled true \ --user-arn arn:aws:quicksight:us-east-1:111122223333:user/default/QuickSightEmbeddingAnonymousPolicy/embeddingsession

有关使用该操作的更多信息,请参阅 GetDashboardEmbedUrl。您可以在自己的代码中使用该 API 操作和其他操作。