本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
步驟 2:獲取帶有身分驗證碼的 URL
重要
Amazon QuickSight 有用於嵌入分析的新 API:GenerateEmbedUrlForAnonymousUser
和GenerateEmbedUrlForRegisteredUser
.
您仍然可以使用GetDashboardEmbedUrl
和 GetSessionEmbedUrl
API 嵌入儀表板和 QuickSight 控制台,但它們不包含最新的嵌入功能。如需最新的 up-to-date 嵌入體驗,請參閱將 QuickSight 分析內嵌到您的應用程式中。
在下一章節,您可以了解如何在您的應用程式伺服器上驗證使用者,以及取得可內嵌的儀表板 URL。
當使用者存取您的應用程式時,該應用程式代表使用者擔任 IAM 角色。然後它將用戶添加到 QuickSight,如果該用戶不存在。接著,它傳遞識別符當作唯一的角色工作階段 ID。
執行上述步驟可確保儀表板的每個檢視器都在中唯一佈建 QuickSight。它還會強制執行個別使用者設定,例如資料列層級的安全性和參數的動態預設值。
下列範例會代表使用者執行 IAM 身分驗證。此代碼在您的應用程式伺服器上運行。
- Java
-
import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicSessionCredentials; 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; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.model.AssumeRoleRequest; import com.amazonaws.services.securitytoken.model.AssumeRoleResult; /** * Class to call QuickSight AWS SDK to get url for dashboard embedding. */ public class GetQuicksightEmbedUrlIAMAuth { private static String IAM = "IAM"; private final AmazonQuickSight quickSightClient; private final AWSSecurityTokenService awsSecurityTokenService; public GetQuicksightEmbedUrlIAMAuth(final AWSSecurityTokenService awsSecurityTokenService) { 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(); this.awsSecurityTokenService = awsSecurityTokenService; } public String getQuicksightEmbedUrl( final String accountId, // YOUR AWS ACCOUNT ID final String dashboardId, // YOUR DASHBOARD ID TO EMBED final String openIdToken, // TOKEN TO ASSUME ROLE WITH ROLEARN final String roleArn, // IAM USER ROLE TO USE FOR EMBEDDING final String sessionName, // SESSION NAME FOR THE ROLEARN ASSUME ROLE 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 { AssumeRoleRequest request = new AssumeRoleRequest() .withRoleArn(roleArn) .withRoleSessionName(sessionName) .withTokenCode(openIdToken) .withDurationSeconds(3600); AssumeRoleResult assumeRoleResult = awsSecurityTokenService.assumeRole(request); AWSCredentials temporaryCredentials = new BasicSessionCredentials( assumeRoleResult.getCredentials().getAccessKeyId(), assumeRoleResult.getCredentials().getSecretAccessKey(), assumeRoleResult.getCredentials().getSessionToken()); AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider(temporaryCredentials); GetDashboardEmbedUrlRequest getDashboardEmbedUrlRequest = new GetDashboardEmbedUrlRequest() .withDashboardId(dashboardId) .withAwsAccountId(accountId) .withIdentityType(IAM) .withResetDisabled(resetDisabled) .withUndoRedoDisabled(undoRedoDisabled) .withRequestCredentialsProvider(awsStaticCredentialsProvider); 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 openIdToken, // TOKEN TO ASSUME ROLE WITH ROLEARN roleArn, // IAM USER ROLE TO USE FOR EMBEDDING sessionName, // SESSION NAME FOR THE ROLEARN ASSUME ROLE 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 stsClient = new AWS.STS(); let stsParams = { RoleSessionName: sessionName, WebIdentityToken: openIdToken, RoleArn: roleArn } stsClient.assumeRoleWithWebIdentity(stsParams, function(err, data) { if (err) { console.log('Error assuming role'); console.log(err, err.stack); errorCallback(err); } else { const getDashboardParams = { AwsAccountId: accountId, DashboardId: dashboardId, IdentityType: 'IAM', ResetDisabled: resetDisabled, SessionLifetimeInMinutes: 600, UndoRedoDisabled: undoRedoDisabled }; const quicksightGetDashboard = new AWS.QuickSight({ region: process.env.
AWS_REGION
, credentials: { accessKeyId: data.Credentials.AccessKeyId, secretAccessKey: data.Credentials.SecretAccessKey, sessionToken: data.Credentials.SessionToken, expiration: data.Credentials.Expiration } }); 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 # 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 # openIdToken: TOKEN TO ASSUME ROLE WITH ROLEARN # roleArn: IAM USER ROLE TO USE FOR EMBEDDING # sessionName: SESSION NAME FOR THE ROLEARN ASSUME ROLE # resetDisabled: PARAMETER TO ENABLE DISABLE RESET BUTTON IN EMBEDDED DASHBAORD # undoRedoDisabled: PARAMETER TO ENABLE DISABLE UNDO REDO BUTTONS IN EMBEDDED DASHBAORD def getDashboardURL(accountId, dashboardId, openIdToken, roleArn, sessionName, resetDisabled, undoRedoDisabled): try: assumedRole = sts.assume_role( RoleArn = roleArn, RoleSessionName = sessionName, WebIdentityToken = openIdToken ) except ClientError as e: return "Error assuming role: " + str(e) else: assumedRoleSession = boto3.Session( aws_access_key_id = assumedRole['Credentials']['AccessKeyId'], aws_secret_access_key = assumedRole['Credentials']['SecretAccessKey'], aws_session_token = assumedRole['Credentials']['SessionToken'], ) try: quickSight = assumedRoleSession.client('quicksight',region_name='
us-east-1
') response = quickSight.get_dashboard_embed_url( AwsAccountId = accountId, DashboardId = dashboardId, IdentityType = 'IAM', 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: return "Error generating embeddedURL: " + str(e) - Node.js
-
下列範例顯示您可以在應用程式伺服器上使用的 JavaScript (Node.js),以取得內嵌儀表板的 URL。您可以在您的網站或應用程式中使用此 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': '1c1fe111-e2d2-3b30-44ef-a0e111111cde', 'IdentityType': 'IAM', 'ResetDisabled': true, 'SessionLifetimeInMinutes': 100, 'UndoRedoDisabled': false, 'StatePersistenceEnabled': 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#
-
以下範例顯示的 .NET/C# 程式碼可在應用程式伺服器上用來取得內嵌儀表板的 URL。您可以在您的網站或應用程式中使用此 URL 來顯示儀表板。
var client = new AmazonQuickSightClient( AccessKey, SecretAccessKey, sessionToken, Amazon.RegionEndpoint.USEast1); try { Console.WriteLine( client.GetDashboardEmbedUrlAsync(new GetDashboardEmbedUrlRequest { AwsAccountId = “
111122223333
”, DashboardId ="1c1fe111-e2d2-3b30-44ef-a0e111111cde"
, IdentityType = EmbeddingIdentityType.IAM, ResetDisabled = true, SessionLifetimeInMinutes = 100, UndoRedoDisabled = false, StatePersistenceEnabled = 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
的許可。如果您正在採取一 just-in-time 種方法在使用者第一次開啟儀表板時新增使用者,則該角色還需要為其啟用權限quicksight:RegisterUser
。aws sts assume-role \ --role-arn "
arn:aws:iam::111122223333:role/embedding_quicksight_dashboard_role
" \ --role-session-namejohn.doe@example.com
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/john.doe@example.com
。角色工作階段 ID 由來自role-arn
和role-session-name
值的角色名稱所組成。對每個使用者使用唯一的角色工作階段 ID,可確保為每個使用者設定適當的許可。還能避免對使用者存取進行任何調節。節流是一項安全性功能,可防止相同使用者 QuickSight 從多個位置存取。角色工作階段 ID 也會在 QuickSight 中變成使用者名稱。您可以使用此模式提 QuickSight 前佈建使用者,或在使用者第一次存取儀表板時佈建使用者。
以下範例顯示可用來佈建使用者的 CLI 命令。有關RegisterUserDescribeUser、和其他 QuickSight API 操作的更多信息,請參閱 QuickSight API 參考。
aws quicksight register-user \ --aws-account-id
111122223333
\ --namespace default \ --identity-typeIAM
\ --iam-arn "arn:aws:iam::111122223333:role/embedding_quicksight_dashboard_role
" \ --user-roleREADER
\ --user-namejhnd
\ --session-name "john.doe@example.com
" \ --emailjohn.doe@example.com
\ --regionus-east-1
\ --custom-permissions-nameTeamA1
如果使用者是透過 Microsoft AD 進行身分驗證,您就不需要使用
RegisterUser
設定他們。相反,他們應該在第一次訪問時自動訂閱 QuickSight。若是 Microsoft AD 使用者,您可以使用DescribeUser
取得使用者的 ARN。使用者第一次存取時 QuickSight,您也可以將此使用者新增至共用儀表板的群組。以下範例顯示用於將使用者新增至群組的 CLI 命令。
aws quicksight create-group-membership \ --aws-account-id=
111122223333
\ --namespace=default \ --group-name=financeusers
\ --member-name="embedding_quicksight_dashboard_role/john.doe@example.com
"您現在擁有應用程序的用戶,該用戶也是該用戶 QuickSight,並且可以訪問儀表板。
最後,為了取得儀表板的簽章 URL,請從應用程式伺服器呼叫
get-dashboard-embed-url
。這會傳回可內嵌的儀表板 URL。以下範例說明如何使用伺服器端呼叫,為透過 AWS Managed Microsoft AD 或 IAM Identity Center 進行身分驗證的使用者取得內嵌式儀表板的 URL。aws quicksight get-dashboard-embed-url \ --aws-account-id
111122223333
\ --dashboard-id1a1ac2b2-3fc3-4b44-5e5d-c6db6778df89
\ --identity-typeIAM
\ --session-lifetime-in-minutes30
\ --undo-redo-disabledtrue
\ --reset-disabledtrue
\ --state-persistence-enabledtrue
\ --user-arn arn:aws:quicksight:us-east-1:111122223333:user/default/embedding_quicksight_dashboard_role/embeddingsession如需有關使用此操作的詳細資訊,請參閱 GetDashboardEmbedUrl。您可以在您自己的程式碼中使用這個和其他 API 操作。
-