Docs Menu

Embed an Authenticated Chart using a Custom JWT Provider

On this page

  • Prerequisites
  • Procedures
  • Enable Authenticated Embedding for a Chart
  • Configure Charts to use your Custom JWT Provider
  • Create a Web App to Display your Chart
  • Customize the Node.js App

Many websites use authentication systems that generate JWTs to represent a signed-in user. If your website produces JWTs, you can configure Charts to validate the existing tokens to authorize the rendering of embedded charts. Alternatively, if your site does not already use JWTs as a part of the authentication process, you can write code to generate JWTs explicitly for the purpose of authorizing chart renders.

This tutorial shows the latter approach. The example shows you how to generate a simple JWT for a logged in user and send it to Charts.

Charts uses the details you provided when you configure a provider to validate JWTs it receives with requests to render embedded charts. If the token is invalid or does not conform to the details you provided, Charts doesn't render the authenticated chart view.

Enable authenticated embedding to generate a Charts Base URL and a chart ID. You will need your Charts Base URL and chart ID to display your chart on a web page.

1

From your dashboard page, select the dashboard containing the chart you wish to embed.

2

From the dashboard, click at the top-right of the chart to access its embedding information. Select Embed Chart from the dropdown menu.

3

If you have already enabled external sharing on the data source this chart uses, skip this step. If you haven't yet enabled embedding on the data source, you can do so now. Click the Configure external sharing link.

4
Embed authenticated chart
5
6

You can specify a function to inject a MongoDB filter document for each user who views the chart. This is useful for rendering user-specific charts.

Example

The following filter function only renders data where the ownerId field of a document matches the value of the Embedding Authentication Provider's token's sub field:

function getFilter(context) {
return { ownerId: context.token.sub };
}
Tip
See also:

To learn more about injecting filters per user, see Inject User-Specific Filters.

7

Specify the fields on which chart viewers can filter data. By default, no fields are specified, meaning the chart cannot be filtered until you explicitly allow at least one field.

Tip
See also:

To learn more about filterable fields, see Specify Filterable Fields.

8

Use these values in your application code together with your Embedded Authentication Provider attributes to embed your chart.

Note

When you configure authentication using a custom JWT provider, you can choose the signing algorithm. This tutorial uses the HS256 signing algorithm. If you select the RS256 signing algorithm, you can also choose one of the following signing keys:

  • JSON web key (JWK) or JSON web key set (JWKS) URL: Charts retrieves the key from the JWK or JWKS file at the specified URL. Charts then uses the key to validate the JSON web token. If there are multiple keys in the file, Charts tries each key until it finds a match.
  • PEM public key: Charts uses the specified public key to verify the JSON web token.
1
  1. If Charts is not already displayed, click Charts in the navigation bar.
  2. Click Charts Settings in the sidebar.
2
3
Field
Value
Name
Enter charts-jwt-tutorial.
Provider
Select Custom JSON Web Token.
Signing Algorithm
Select HS256.
Signing Key
Enter topsecret.
4

If you already have an app in which to display your chart, you’re all set. If not, proceed with the remaining steps.

MongoDB offers a pre-built sample that shows you how to use the Embedding SDK to authenticate an embedded chart using a JWT.

Clone the GitHub repository and follow the instructions in the Readme file to begin using the app. You can customize it to use the chart you created earlier.

1
Warning

Generate JWTs server-side to protect your signing keys from exposure.

The app.js file in the sample application uses a simple web service and the jsonwebtoken package to generate and return a JWT signed using the HS256 algorithm when a user logs in to the application with these credentials:

  • User name: admin
  • Password: password
1const express = require("express");
2const bodyParser = require("body-parser");
3const cors = require("cors");
4const jwt = require("jsonwebtoken");
5const config = require("./config.js");
6
7const app = express();
8const port = 8000;
9
10// Configuring body parser middleware
11app.use(bodyParser.urlencoded({ extended: false }));
12app.use(bodyParser.json());
13app.use(cors());
14
15app.post("/login", (req, res) => {
16 const loginDetails = req.body;
17 // mock a check against the database
18 let mockedUsername = "admin";
19 let mockedPassword = "password";
20
21 if (
22 loginDetails &&
23 loginDetails.username === mockedUsername &&
24 loginDetails.password === mockedPassword
25 ) {
26 let token = jwt.sign({ username: loginDetails.username }, config.secret, {
27 expiresIn: "24h" // expires in 24 hours
28 });
29 res.json({ bearerToken: token });
30 } else {
31 res.status(401).send(false);
32 }
33});
34
35app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Note

Your application must handle refreshing or issuing new tokens before they expire.

In the sample application, the signing key topsecret is defined in a file in your application named config.js:

module.exports = {
secret: "topsecret"
};
2
  1. Create a new object from the ChartsEmbedSDK class. Provide:

    • The value of the baseUrl property with the URL that points to your Charts instance. To embed one of your charts in the sample application, replace this value with the :guilabel:Base URL from your Embed Chart dialog.
    • The chartId property to specify the unique identifier of the chart you want to embed. To embed one of your charts in the sample application, replace this value with the :guilabel:Chart ID from your Embed Chart dialog.
    • The getUserToken property to specify the function that generates and returns a JWT from your authentication provider.
    • Any optional properties you want to provide. For a list of all properties you can use when you embed charts using the SDK, see SDK option reference.

    In the src/index.js file in the sample application, the login function in the getUserToken property calls the web service you created to generate a JWT. If login is successful, that function returns a valid JWT to the getUserToken property.

    1import ChartsEmbedSDK from "@mongodb-js/charts-embed-dom";
    2import "regenerator-runtime/runtime";
    3
    4document
    5 .getElementById("loginButton")
    6 .addEventListener("click", async () => await tryLogin());
    7
    8function getUser() {
    9return document.getElementById("username").value;
    10}
    11
    12function getPass() {
    13return document.getElementById("password").value;
    14}
    15
    16async function tryLogin() {
    17if (await login(getUser(), getPass())) {
    18 document.body.classList.toggle("logged-in", true);
    19 await renderChart();
    20}
    21}
    22
    23async function login(username, password) {
    24const rawResponse = await fetch("http://localhost:8000/login", {
    25 method: "POST",
    26 headers: {
    27 Accept: "application/json",
    28 "Content-Type": "application/json"
    29 },
    30 body: JSON.stringify({ username: username, password: password })
    31});
    32const content = await rawResponse.json();
    33
    34return content.bearerToken;
    35}
    36
    37async function renderChart() {
    38const sdk = new ChartsEmbedSDK({
    39 baseUrl: "https://localhost/mongodb-charts-iwfxn", // ~REPLACE~ with the Base URL from your Embed Chart dialog
    40 chartId: "d98f67cf-374b-4823-a2a8-f86e9d480065", // ~REPLACE~ with the Chart ID from your Embed Chart dialog
    41 getUserToken: async function() {
    42 return await login(getUser(), getPass());
    43 }
    44});
  2. For each chart that you want to embed, invoke the CreateChart method of the object you just created. To embed one of your charts in the sample application, replace the value of the id property with the :guilabel:Chart ID from your Embed Chart dialog.

    The following example shows an invocation of the CreateChart method in the src/index.js file in the sample application.

    const chart = sdk.createChart({ chartId: "d98f67cf-374b-4823-a2a8-f86e9d480065" }); // ~REPLACE~ with the Chart ID from your Embed Chart dialog
3

Use the render method of your chart object to render it in your application.

The following example shows an invocation of the render method in the src/index.js file in the sample application.

chart.render(document.getElementById("chart"));
4

Charts renders the chart if it can validate the token it received with the request to render the chart. If the token isn't valid, Charts doesn't render the chart and displays an error code.

For more information on the Charts embedding error codes, see Embedded Chart Error Codes.

Give Feedback
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.