Step 2: Generate the URL with the authentication code attached
In the following section, you can find out how to authenticate your user and get the embeddable dashboard URL on your application server. If you plan to embed dashboards for IAM or QuickSight identity types, share the dashboard with the users.
When a user accesses your app, the app assumes the IAM role on the user's behalf. Then it adds the user to QuickSight, if that user doesn't already exist. Next, it passes an identifier as the unique role session ID.
Performing these steps ensures that each viewer of the dashboard is uniquely provisioned in QuickSight. It also enforces per-user settings, such as the row-level security and dynamic defaults for parameters.
The following examples perform the IAM authentication on the user's behalf. This code runs on your app server.
- 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.GenerateEmbedUrlForRegisteredUserRequest; import com.amazonaws.services.quicksight.model.GenerateEmbedUrlForRegisteredUserResult; import com.amazonaws.services.quicksight.model.RegisteredUserEmbeddingExperienceConfiguration; import com.amazonaws.services.quicksight.model.RegisteredUserDashboardEmbeddingConfiguration; /** * Class to call QuickSight Amazon SDK to get url for dashboard embedding. */ public class GetQuicksightEmbedUrlRegisteredUserDashboardEmbedding { private final AmazonQuickSight quickSightClient; public GetQuicksightEmbedUrlRegisteredUserDashboardEmbedding() { 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, // Amazon Account ID final String dashboardId, // Dashboard ID to embed final List<String> allowedDomains, // Runtime allowed domain for embedding final String userArn // Registered user arn to use for embedding. Refer to Get Embed Url section in developer portal to find out how to get user arn for a QuickSight user. ) throws Exception { final RegisteredUserEmbeddingExperienceConfiguration experienceConfiguration = new RegisteredUserEmbeddingExperienceConfiguration() .withDashboard(new RegisteredUserDashboardEmbeddingConfiguration().withInitialDashboardId(dashboardId)); final GenerateEmbedUrlForRegisteredUserRequest generateEmbedUrlForRegisteredUserRequest = new GenerateEmbedUrlForRegisteredUserRequest(); generateEmbedUrlForRegisteredUserRequest.setAwsAccountId(accountId); generateEmbedUrlForRegisteredUserRequest.setUserArn(userArn); generateEmbedUrlForRegisteredUserRequest.setAllowedDomains(allowedDomains); generateEmbedUrlForRegisteredUserRequest.setExperienceConfiguration(experienceConfiguration); final GenerateEmbedUrlForRegisteredUserResult generateEmbedUrlForRegisteredUserResult = quickSightClient.generateEmbedUrlForRegisteredUser(generateEmbedUrlForRegisteredUserRequest); return generateEmbedUrlForRegisteredUserResult.getEmbedUrl(); } }
- JavaScript
-
global.fetch = require('node-fetch'); const Amazon = require('aws-sdk'); function generateEmbedUrlForRegisteredUser( accountId, dashboardId, openIdToken, // Cognito-based token userArn, // registered user arn roleArn, // IAM user role to use for embedding sessionName, // Session name for the roleArn assume role allowedDomains, // Runtime allowed domain for embedding 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, "ExperienceConfiguration": { "Dashboard": { "InitialDashboardId": dashboardId } }, "UserArn": userArn, "AllowedDomains": allowedDomains, "SessionLifetimeInMinutes": 600 }; const quicksightClient = 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 } }); quicksightClient.generateEmbedUrlForRegisteredUser(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 sts = boto3.client('sts') # Function to generate embedded URL # accountId: AWS account ID # dashboardId: Dashboard ID to embed # userArn: arn of registered user # allowedDomains: Runtime allowed domain for embedding # roleArn: IAM user role to use for embedding # sessionName: session name for the roleArn assume role def getEmbeddingURL(accountId, dashboardId, userArn, allowedDomains, roleArn, sessionName): try: assumedRole = sts.assume_role( RoleArn = roleArn, RoleSessionName = sessionName, ) 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: quicksightClient = assumedRoleSession.client('quicksight', region_name='us-west-2') response = quicksightClient.generate_embed_url_for_registered_user( AwsAccountId=accountId, ExperienceConfiguration = { "Dashboard": { "InitialDashboardId": dashboardId } }, UserArn = userArn, AllowedDomains = allowedDomains, 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: return "Error generating embedding url: " + str(e)
- Node.js
-
The following example shows the JavaScript (Node.js) that you can use on the app server to generate the URL for the embedded dashboard. You can use this URL in your website or app to display the dashboard.
const Amazon = 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.generateEmbedUrlForRegisteredUser({ 'AwsAccountId': '111122223333', 'ExperienceConfiguration': { 'Dashboard': { 'InitialDashboardId': '1c1fe111-e2d2-3b30-44ef-a0e111111cde' } }, 'UserArn': 'REGISTERED_USER_ARN', 'AllowedDomains': allowedDomains, 'SessionLifetimeInMinutes': 100 }, 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...' RequestId: '7bee030e-f191-45c4-97fe-d9faf0e03713' } - .NET/C#
-
The following example shows the .NET/C# code that you can use on the app server to generate the URL for the embedded dashboard. You can use this URL in your website or app to display the dashboard.
using System; using Amazon.QuickSight; using Amazon.QuickSight.Model; namespace GenerateDashboardEmbedUrlForRegisteredUser { class Program { static void Main(string[] args) { var quicksightClient = new AmazonQuickSightClient( AccessKey, SecretAccessKey, SessionToken, Amazon.RegionEndpoint.USEast1); try { RegisteredUserDashboardEmbeddingConfiguration registeredUserDashboardEmbeddingConfiguration = new RegisteredUserDashboardEmbeddingConfiguration { InitialDashboardId = "dashboardId" }; RegisteredUserEmbeddingExperienceConfiguration registeredUserEmbeddingExperienceConfiguration = new RegisteredUserEmbeddingExperienceConfiguration { Dashboard = registeredUserDashboardEmbeddingConfiguration }; Console.WriteLine( quicksightClient.GenerateEmbedUrlForRegisteredUserAsync(new GenerateEmbedUrlForRegisteredUserRequest { AwsAccountId = "111122223333", ExperienceConfiguration = registeredUserEmbeddingExperienceConfiguration, UserArn = "REGISTERED_USER_ARN", AllowedDomains = allowedDomains, SessionLifetimeInMinutes = 100 }).Result.EmbedUrl ); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
- Amazon CLI
-
To assume the role, choose one of the following Amazon Security Token Service (Amazon STS) API operations:
-
AssumeRole – Use this operation when you're using an IAM identity to assume the role.
-
AssumeRoleWithWebIdentity – Use this operation when you're using a web identity provider to authenticate your user.
-
AssumeRoleWithSaml – Use this operation when you're using SAML to authenticate your users.
The following example shows the CLI command to set the IAM role. The role needs to have permissions enabled for
quicksight:GenerateEmbedUrlForRegisteredUser
. If you are taking a just-in-time approach to add users when they first open a dashboard, the role also needs permissions enabled forquicksight:RegisterUser
.aws sts assume-role \ --role-arn "
arn:aws-cn:iam::111122223333:role/embedding_quicksight_dashboard_role
" \ --role-session-namejohn.doe@example.com
The
assume-role
operation returns three output parameters: the access key, the secret key, and the session token.Note
If you get an
ExpiredToken
error when calling theAssumeRole
operation, this is probably because the previousSESSION TOKEN
is still in the environment variables. Clear this by setting the following variables:-
AWS_ACCESS_KEY_ID
-
AWS_SECRET_ACCESS_KEY
-
AWS_SESSION_TOKEN
The following example shows how to set these three parameters in the CLI. If you're using a Microsoft Windows machine, use
set
instead ofexport
.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
"Running these commands sets the role session ID of the user visiting your website to
embedding_quicksight_dashboard_role/john.doe@example.com
. The role session ID is made up of the role name fromrole-arn
and therole-session-name
value. Using the unique role session ID for each user ensures that appropriate permissions are set for each user. It also prevents any throttling of user access. Throttling is a security feature that prevents the same user from accessing QuickSight from multiple locations.The role session ID also becomes the user name in QuickSight. You can use this pattern to provision your users in QuickSight ahead of time, or to provision them the first time they access the dashboard.
The following example shows the CLI command that you can use to provision a user. For more information about RegisterUser
, DescribeUser , and other QuickSight API operations, see the QuickSight API Reference . aws quicksight register-user \ --aws-account-id
111122223333
\ --namespacedefault
\ --identity-typeIAM
\ --iam-arn "arn:aws-cn: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
If your user is authenticated through Microsoft AD, you don't need to use
RegisterUser
to set them up. Instead, they should be automatically subscribed the first time they access QuickSight. For Microsoft AD users, you can useDescribeUser
to get the user ARN.The first time a user accesses QuickSight, you can also add this user to the group that the dashboard is shared with. The following example shows the CLI command to add a user to a group.
aws quicksight create-group-membership \ --aws-account-id=
111122223333
\ --namespace=default \ --group-name=financeusers
\ --member-name="embedding_quicksight_dashboard_role/john.doe@example.com
"You now have a user of your app who is also a user of QuickSight, and who has access to the dashboard.
Finally, to get a signed URL for the dashboard, call
generate-embed-url-for-registered-user
from the app server. This returns the embeddable dashboard URL. The following example shows how to generate the URL for an embedded dashboard using a server-side call for users authenticated through Amazon Managed Microsoft AD or single sign-on (IAM Identity Center).aws quicksight generate-embed-url-for-registered-user \ --aws-account-id
111122223333
\ --session-lifetime-in-minutes600
\ --user-arnarn:aws-cn:quicksight:us-east-1:111122223333:user/default/embedding_quicksight_visual_role/embeddingsession
\ --allowed-domains '["domain1
","domain2
"]' \ --experience-configuration Dashboard={InitialDashboardId=1a1ac2b2-3fc3-4b44-5e5d-c6db6778df89
}For more information about using this operation, see GenerateEmbedUrlForRegisteredUser
. You can use this and other API operations in your own code. -