內嵌 QuickSight匿名 (未註冊) 使用者的視覺效果 - Amazon QuickSight

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

內嵌 QuickSight匿名 (未註冊) 使用者的視覺效果

 適用於:企業版本 
   目標對象:Amazon QuickSight 開發人員 

在下列各節中,您可以找到如何為匿名 (未註冊) 使用者設定內嵌 Amazon QuickSight 視覺效果的詳細資訊。

步驟 1:設定許可

 適用於:企業版 
   目標對象:Amazon QuickSight 開發人員 

在以下章節中,您可以了解如何為後端應用程式或 Web 伺服器設定許可。此任務需要 的管理存取權IAM。

每個存取視覺效果的使用者都會擔任一個角色,讓他們可以 QuickSight 存取視覺效果並取得許可。若要實現此目的,請在 中建立 IAM角色 AWS 帳戶。將IAM政策與 角色建立關聯,以便為擔任該角色的任何使用者提供許可。

您可以在IAM政策中建立條件,以限制開發人員可以在 GenerateEmbedUrlForAnonymousUser API 操作的 AllowedDomains 參數中列出的網域。AllowedDomains 參數是選用參數。它會授予您作為開發人員覆寫管理 QuickSight功能表中設定的靜態網域的選項。反之,您最多可以列出三個可以存取產生的 的網域或子網域URL。這接著URL會內嵌在您建立的網站中。只有參數中列出的域可以存取內嵌式儀表板。如果沒有這種情況,您可以在 AllowedDomains 參數中列出網際網路上的任何域。

若要限制開發人員可搭配此參數使用的網域,請將 AllowedEmbeddingDomains條件新增至您的IAM政策。如需 AllowedDomains 參數的詳細資訊,請參閱《Amazon QuickSight API 參考GenerateEmbedUrlForAnonymousUser》中的 。

下列範例政策提供搭配 GenerateEmbedUrlForAnonymousUser 使用的許可。若要使這種方法生效,您的 AWS 帳戶還需要一個工作階段套件。或工作階段容量定價。否則,當使用者嘗試存取視覺效果時,就會傳回錯誤 UnsupportedPricingPlanException

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "quicksight:GenerateEmbedUrlForAnonymousUser" ], "Resource": [ "arn:{{partition}}:quicksight:{{region}}:{{accountId}}:namespace/{{namespace}}", "arn:{{partition}}:quicksight:{{region}}:{{accountId}}:dashboard/{{dashboardId-1}}", "arn:{{partition}}:quicksight:{{region}}:{{accountId}}:dashboard/{{dashboardId-2}}" ], "Condition": { "ForAllValues:StringEquals": { "quicksight:AllowedEmbeddingDomains": [ "https://my.static.domain1.com", "https://*.my.static.domain2.com" ] } } } }

您應用程式的IAM身分必須具有與其相關聯的信任政策,以允許存取您剛建立的角色。這表示當使用者存取您的應用程式時,您的應用程式可代表使用者擔任該角色,並開啟視覺效果。範例信任政策如下所示。

{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowLambdaFunctionsToAssumeThisRole", "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }, { "Sid": "AllowEC2InstancesToAssumeThisRole", "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }

如需信任政策的詳細資訊,請參閱IAM《 使用者指南中的暫時安全登入IAM資料。

步驟 2:產生URL已連接驗證碼的

 適用於:企業版 
   目標對象:Amazon QuickSight 開發人員 

在下一節中,您可以找到如何代表匿名訪客進行身分驗證,並在應用程式伺服器上取得可內嵌URL的視覺效果。

當使用者存取您的應用程式時,應用程式會代表使用者擔任該IAM角色。然後,如果使用者尚未存在 QuickSight,它會將使用者新增至 。接著,它傳遞識別符當作唯一的角色工作階段 ID。

下列範例代表使用者執行IAM身分驗證。它傳遞識別符當作唯一的角色工作階段 ID。此代碼在您的應用程式伺服器上運行。

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.AnonymousUserDashboardVisualEmbeddingConfiguration; import com.amazonaws.services.quicksight.model.AnonymousUserEmbeddingExperienceConfiguration; import com.amazonaws.services.quicksight.model.DashboardVisualId; import com.amazonaws.services.quicksight.model.GenerateEmbedUrlForAnonymousUserRequest; import com.amazonaws.services.quicksight.model.GenerateEmbedUrlForAnonymousUserResult; import com.amazonaws.services.quicksight.model.SessionTag; import java.util.List; /** * Class to call QuickSight AWS SDK to get url for Visual embedding. */ public class GenerateEmbedUrlForAnonymousUserTest { private final AmazonQuickSight quickSightClient; public GenerateEmbedUrlForAnonymousUserTest() { 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 getEmbedUrl( final String accountId, // AWS Account ID final String namespace, // Anonymous embedding required specifying a valid namespace for which you want the enbedding URL final List<String> authorizedResourceArns, // Dashboard arn list of dashboard visuals to embed final String dashboardId, // Dashboard ID of the dashboard to embed final String sheetId, // Sheet ID of the sheet to embed final String visualId, // Visual ID of the visual to embed final List<String> allowedDomains, // Runtime allowed domains for embedding final List<SessionTag> sessionTags // Session tags used for row-level security ) throws Exception { final DashboardVisualId dashboardVisual = new DashboardVisualId() .withDashboardId(dashboardId) .withSheetId(sheetId) .withVisualId(visualId); final AnonymousUserDashboardVisualEmbeddingConfiguration anonymousUserDashboardVisualEmbeddingConfiguration = new AnonymousUserDashboardVisualEmbeddingConfiguration() .withInitialDashboardVisualId(dashboardVisual); final AnonymousUserEmbeddingExperienceConfiguration anonymousUserEmbeddingExperienceConfiguration = new AnonymousUserEmbeddingExperienceConfiguration() .withDashboardVisual(anonymousUserDashboardVisualEmbeddingConfiguration); final GenerateEmbedUrlForAnonymousUserRequest generateEmbedUrlForAnonymousUserRequest = new GenerateEmbedUrlForAnonymousUserRequest() .withAwsAccountId(accountId) .withNamespace(namespace) // authorizedResourceArns should contain ARN of dashboard used below in ExperienceConfiguration .withAuthorizedResourceArns(authorizedResourceArns) .withExperienceConfiguration(anonymousUserEmbeddingExperienceConfiguration) .withAllowedDomains(allowedDomains) .withSessionTags(sessionTags) .withSessionLifetimeInMinutes(600L); final GenerateEmbedUrlForAnonymousUserResult generateEmbedUrlForAnonymousUserResult = quickSightClient.generateEmbedUrlForAnonymousUser(generateEmbedUrlForAnonymousUserRequest); return generateEmbedUrlForAnonymousUserResult.getEmbedUrl(); } }
global.fetch = require('node-fetch'); const AWS = require('aws-sdk'); function generateEmbedUrlForAnonymousUser( accountId, // Your AWS account ID dashboardId, // Dashboard ID to which the constructed url points sheetId, // Sheet ID to which the constructed url points visualId, // Visual ID to which the constructed url points quicksightNamespace, // valid namespace where you want to do embedding authorizedResourceArns, // dashboard arn list of dashboard visuals to embed allowedDomains, // runtime allowed domains for embedding sessionTags, // session tags used for row-level security generateEmbedUrlForAnonymousUserCallback, // success callback method errorCallback // error callback method ) { const experienceConfiguration = { "DashboardVisual": { "InitialDashboardVisualId": { "DashboardId": dashboardId, "SheetId": sheetId, "VisualId": visualId } } }; const generateEmbedUrlForAnonymousUserParams = { "AwsAccountId": accountId, "Namespace": quicksightNamespace, // authorizedResourceArns should contain ARN of dashboard used below in ExperienceConfiguration "AuthorizedResourceArns": authorizedResourceArns, "AllowedDomains": allowedDomains, "ExperienceConfiguration": experienceConfiguration, "SessionTags": sessionTags, "SessionLifetimeInMinutes": 600 }; const quicksightClient = new AWS.QuickSight({ region: process.env.AWS_REGION, credentials: { accessKeyId: AccessKeyId, secretAccessKey: SecretAccessKey, sessionToken: SessionToken, expiration: Expiration } }); quicksightClient.generateEmbedUrlForAnonymousUser(generateEmbedUrlForAnonymousUserParams, 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 THIS API "Access-Control-Allow-Headers": "Content-Type" }, "body": JSON.stringify(data), "isBase64Encoded": false } generateEmbedUrlForAnonymousUserCallback(result); } }); }
import json import boto3 from botocore.exceptions import ClientError import time # Create QuickSight and STS clients quicksightClient = boto3.client('quicksight',region_name='us-west-2') sts = boto3.client('sts') # Function to generate embedded URL for anonymous user # accountId: YOUR AWS ACCOUNT ID # quicksightNamespace: VALID NAMESPACE WHERE YOU WANT TO DO NOAUTH EMBEDDING # authorizedResourceArns: DASHBOARD ARN LIST TO EMBED # allowedDomains: RUNTIME ALLOWED DOMAINS FOR EMBEDDING # experienceConfiguration: DASHBOARD ID, SHEET ID and VISUAL ID TO WHICH THE CONSTRUCTED URL POINTS # Example experienceConfig -> 'DashboardVisual': { # 'InitialDashboardVisualId': { # 'DashboardId': 'dashboardId', # 'SheetId': 'sheetId', # 'VisualId': 'visualId' # } # }, # sessionTags: SESSION TAGS USED FOR ROW-LEVEL SECURITY def generateEmbedUrlForAnonymousUser(accountId, quicksightNamespace, authorizedResourceArns, allowedDomains, experienceConfiguration, sessionTags): try: response = quicksightClient.generate_embed_url_for_anonymous_user( AwsAccountId = accountId, Namespace = quicksightNamespace, AuthorizedResourceArns = authorizedResourceArns, AllowedDomains = allowedDomains, ExperienceConfiguration = experienceConfiguration, SessionTags = sessionTags, SessionLifetimeInMinutes = 600 ) 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)

下列範例顯示您可以在應用程式伺服器上使用的 JavaScript (Node.js),以URL為內嵌儀表板產生 。您可以在URL網站或應用程式中使用此項目來顯示儀表板。

const AWS = require('aws-sdk'); const https = require('https'); var quicksightClient = new AWS.Service({ apiConfig: require('./quicksight-2018-04-01.min.json'), region: 'us-east-1', }); quicksightClient.generateEmbedUrlForAnonymousUser({ 'AwsAccountId': '111122223333', 'Namespace' : 'default', // authorizedResourceArns should contain ARN of dashboard used below in ExperienceConfiguration 'AuthorizedResourceArns': authorizedResourceArns, 'ExperienceConfiguration': { 'DashboardVisual': { 'InitialDashboardVisualId': { 'DashboardId': 'dashboard_id', 'SheetId': 'sheet_id', 'VisualId': 'visual_id' } } }, 'AllowedDomains': allowedDomains, 'SessionTags': sessionTags, 'SessionLifetimeInMinutes': 600 }, 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://quicksightdomain/embed/12345/dashboards/67890/sheets/12345/visuals/67890...", "RequestId": "7bee030e-f191-45c4-97fe-d9faf0e03713" }

下列範例顯示 。NET/您可以在應用程式伺服器上使用的 C# 程式碼,為URL內嵌儀表板產生 。您可以在URL網站或應用程式中使用此項目來顯示儀表板。

using System; using Amazon.QuickSight; using Amazon.QuickSight.Model; namespace GenerateDashboardEmbedUrlForAnonymousUser { class Program { static void Main(string[] args) { var quicksightClient = new AmazonQuickSightClient( AccessKey, SecretAccessKey, SessionToken, Amazon.RegionEndpoint.USEast1); try { DashboardVisualId dashboardVisual = new DashboardVisualId { DashboardId = "dashboard_id", SheetId = "sheet_id", VisualId = "visual_id" }; AnonymousUserDashboardVisualEmbeddingConfiguration anonymousUserDashboardVisualEmbeddingConfiguration = new AnonymousUserDashboardVisualEmbeddingConfiguration { InitialDashboardVisualId = dashboardVisual }; AnonymousUserEmbeddingExperienceConfiguration anonymousUserEmbeddingExperienceConfiguration = new AnonymousUserEmbeddingExperienceConfiguration { DashboardVisual = anonymousUserDashboardVisualEmbeddingConfiguration }; Console.WriteLine( quicksightClient.GenerateEmbedUrlForAnonymousUserAsync(new GenerateEmbedUrlForAnonymousUserRequest { AwsAccountId = "111222333444", Namespace = default, // authorizedResourceArns should contain ARN of dashboard used below in ExperienceConfiguration AuthorizedResourceArns = { "dashboard_id" }, ExperienceConfiguration = anonymousUserEmbeddingExperienceConfiguration, SessionTags = sessionTags, SessionLifetimeInMinutes = 600, }).Result.EmbedUrl ); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }

若要擔任角色,請選擇下列其中一個 AWS Security Token Service (AWS STS) API操作:

  • AssumeRole – 當您使用IAM身分擔任角色時,請使用此操作。

  • AssumeRoleWithWebIdentity – 當您使用 Web 身分提供者來驗證使用者時,請使用此操作。

  • AssumeRoleWithSaml – 當您使用安全聲明標記語言 (SAML) 驗證使用者時,請使用此操作。

下列範例顯示 CLI命令來設定IAM角色。角色需要啟用 quicksight:GenerateEmbedUrlForAnonymousUser 的許可。

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_visual_role/QuickSightEmbeddingAnonymousPolicy。角色工作階段 ID 由來自 role-arnrole-session-name 值的角色名稱所組成。對每個使用者使用唯一的角色工作階段 ID,可確保為每個訪問使用者設定適當的許可。它還使每個會話獨立且不同。如果您正在使用 Web 伺服器陣列 (例如負載平衡),且工作階段重新連線到不同的伺服器,則會開始新的工作階段。

若要取得視覺效果URL的簽署,generate-embed-url-for-anynymous-user請從應用程式伺服器呼叫 。這會傳回可內嵌的視覺效果 URL。下列範例示範如何使用伺服器端呼叫,為對 Web 入口網站或應用程式進行匿名存取的使用者產生URL內嵌視覺效果的 。

aws quicksight generate-embed-url-for-anonymous-user \ --aws-account-id 111122223333 \ --namespace default-or-something-else \ --session-lifetime-in-minutes 15 \ --authorized-resource-arns '["dashboard-arn-1","dashboard-arn-2"]' \ --allowed-domains '["domain1","domain2"]' \ --session-tags '["Key": tag-key-1,"Value": tag-value-1,{"Key": tag-key-1,"Value": tag-value-1}]' \ --experience-configuration 'DashboardVisual={InitialDashboardVisualId={DashboardId=dashboard_id,SheetId=sheet_id,VisualId=visual_id}}'

如需使用此操作的詳細資訊,請參閱 GenerateEmbedUrlForAnonymousUser。 您可以在自己的程式碼中使用此操作和其他API操作。

步驟 3:內嵌視覺效果 URL

 適用於:企業版 
   目標對象:Amazon QuickSight 開發人員 

在下一節中,您可以了解如何使用QuickSight 內嵌 SDK (JavaScript) 將URL步驟 2 的視覺效果內嵌到網站或應用程式頁面。您可以使用SDK執行以下操作:

  • 將視覺效果放在HTML頁面上。

  • 將參數傳遞到視覺效果中。

  • 以針對您的應用程式而訂做的訊息來處理錯誤狀態。

呼叫 GenerateEmbedUrlForAnonymousUserAPI操作來產生您可以內嵌在應用程式中URL的 。這URL有效時間為 5 分鐘,而產生的工作階段有效時間為 10 小時。API 操作會提供URL授權 (驗證) 程式碼,以啟用工作階段的單一登入。

以下是 generate-embed-url-for-anonymous-user 的回應範例。quicksightdomain 此範例中的 是您URL用來存取 QuickSight 帳戶的 。

//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://quicksightdomain/embed/12345/dashboards/67890/sheets/12345/visuals/67890...", "RequestId": "7bee030e-f191-45c4-97fe-d9faf0e03713" }

使用內嵌或將此視覺效果新增至 iframe,將此視覺 QuickSight 效果內嵌SDKURL到您的網頁中。若您設定固定的高度和寬度數字 (像素), QuickSight 會使用這些值,而不會隨著您調整視窗大小而改變視覺效果。如果您設定相對百分比高度和寬度, QuickSight 會提供回應式配置,隨著視窗大小變更而修改。透過使用 QuickSight 內嵌 SDK,您也可以控制視覺效果中的參數,並在視覺效果載入完成和錯誤方面接收回呼。

要託管內嵌視覺效果的網域必須位於允許清單上,即 Amazon QuickSight 訂閱的核准網域清單。這項要求將使未獲核准的域無法託管內嵌視覺效果和儀表板,進而保護您的資料。如需為內嵌視覺效果和儀表板新增域的詳細資訊,請參閱 允許在執行時間使用 列出網域 QuickSight API

下列範例示範如何使用產生的 URL。此代碼駐留在您的應用程式伺服器上。

<!DOCTYPE html> <html> <head> <title>Visual Embedding Example</title> <script src="https://unpkg.com/amazon-quicksight-embedding-sdk@2.0.0/dist/quicksight-embedding-js-sdk.min.js"></script> <script type="text/javascript"> const embedVisual = async() => { const { createEmbeddingContext, } = QuickSightEmbedding; const embeddingContext = await createEmbeddingContext({ onChange: (changeEvent, metadata) => { console.log('Context received a change', changeEvent, metadata); }, }); const frameOptions = { url: "<YOUR_EMBED_URL>", // replace this value with the url generated via embedding API container: '#experience-container', height: "700px", width: "1000px", onChange: (changeEvent, metadata) => { switch (changeEvent.eventName) { case 'FRAME_MOUNTED': { console.log("Do something when the experience frame is mounted."); break; } case 'FRAME_LOADED': { console.log("Do something when the experience frame is loaded."); break; } } }, }; const contentOptions = { parameters: [ { Name: 'country', Values: ['United States'], }, { Name: 'states', Values: [ 'California', 'Washington' ] } ], locale: "en-US", onMessage: async (messageEvent, experienceMetadata) => { switch (messageEvent.eventName) { case 'CONTENT_LOADED': { console.log("All visuals are loaded. The title of the document:", messageEvent.message.title); break; } case 'ERROR_OCCURRED': { console.log("Error occured while rendering the experience. Error code:", messageEvent.message.errorCode); break; } case 'PARAMETERS_CHANGED': { console.log("Parameters changed. Changed parameters:", messageEvent.message.changedParameters); break; } case 'SIZE_CHANGED': { console.log("Size changed. New dimensions:", messageEvent.message); break; } } }, }; const embeddedVisualExperience = await embeddingContext.embedVisual(frameOptions, contentOptions); const selectCountryElement = document.getElementById('country'); selectCountryElement.addEventListener('change', (event) => { embeddedVisualExperience.setParameters([ { Name: 'country', Values: event.target.value } ]); }); }; </script> </head> <body onload="embedVisual()"> <span> <label for="country">Country</label> <select id="country" name="country"> <option value="United States">United States</option> <option value="Mexico">Mexico</option> <option value="Canada">Canada</option> </select> </span> <div id="experience-container"></div> </body> </html>
<!DOCTYPE html> <html> <head> <title>Visual Embedding Example</title> <!-- You can download the latest QuickSight embedding SDK version from https://www.npmjs.com/package/amazon-quicksight-embedding-sdk --> <!-- Or you can do "npm install amazon-quicksight-embedding-sdk", if you use npm for javascript dependencies --> <script src="./quicksight-embedding-js-sdk.min.js"></script> <script type="text/javascript"> let embeddedVisualExperience; function onVisualLoad(payload) { console.log("Do something when the visual is fully loaded."); } function onError(payload) { console.log("Do something when the visual fails loading"); } function embedVisual() { const containerDiv = document.getElementById("embeddingContainer"); const options = { url: "<YOUR_EMBED_URL>", // replace this value with the url generated via embedding API container: containerDiv, parameters: { country: "United States" }, height: "700px", width: "1000px", locale: "en-US" }; embeddedVisualExperience = QuickSightEmbedding.embedVisual(options); embeddedVisualExperience.on("error", onError); embeddedVisualExperience.on("load", onVisualLoad); } function onCountryChange(obj) { embeddedVisualExperience.setParameters({country: obj.value}); } </script> </head> <body onload="embedVisual()"> <span> <label for="country">Country</label> <select id="country" name="country" onchange="onCountryChange(this)"> <option value="United States">United States</option> <option value="Mexico">Mexico</option> <option value="Canada">Canada</option> </select> </span> <div id="embeddingContainer"></div> </body> </html>

若要讓此範例運作,請務必使用 Amazon QuickSight Embedding SDK 載入您網站上的內嵌視覺效果 JavaScript。為獲得您的版本,請執行以下其中一項操作: