Articles in this section
Category / Section

Embedding Bold BI in ASP.NET Core with Embed Token Authentication

Published:

This article explains how to generate an embed token for embedding a Bold BI dashboard in an ASP.NET Core 8.0 application. The embed token enables secure dashboard rendering with support for row-level security, group-based authorization, and anonymous user embedding.

How to Generate an Embed Token

To embed a Bold BI dashboard, you must generate an embed token for authentication. The embed token is created by sending a request to the Bold BI server with specific parameters, including the dashboard ID, user details, and embed secret. Follow these steps to generate the token:

  1. Generate the Embed Query String
    Create an embed query string that includes parameters such as the dashboard ID, mode (e.g., view), and expiration time. A unique nonce and timestamp are included for security.
    Example JavaScript code to generate the query string:

    function generateEmbedQueryString(dashboardId, mode, expirationTime) {
        return [
            `embed_nonce=${generateUUID()}`,
            `embed_dashboard_id=${dashboardId}`,
            `embed_mode=${mode}`,
            `embed_timestamp=${Math.floor(Date.now() / 1000)}`,
            `embed_expirationtime=${expirationTime}`
        ].join('&');
    }
    
    function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
    
  2. Send Embed Token Request
    Construct the embed query string and build the request payload containing the dashboard server API URL. Then, call the backend API to request the embed token.

    Example JavaScript code for sending the embed token request:

    function getDashboardAccessToken(dashboardId, mode, expirationTime) {
        const queryString = generateEmbedQueryString(dashboardId, mode, expirationTime);
        const payload = buildRequestPayload(queryString);
        sendAuthorizationRequest(payload, dashboardId);
    }
    
    function buildRequestPayload(queryString) {
        return {
            embedQuerString: queryString,
            dashboardServerApiUrl: `${rootUrl}/api/${siteIdentifier}`
        };
    }
    
  3. Send Authorization Request
    Create a backend API endpoint in your ASP.NET Core application to send the embed query string to the Bold BI server and request an embed token. Optionally, apply row-level security, group-based authorization, or anonymous user settings in this step.

    Example C# code for the backend API endpoint:

    [HttpPost]
    [Route("AuthorizationServer")]
    public string AuthorizationServer([FromBody] object embedQuerString)
    {
        var embedClass = Newtonsoft.Json.JsonConvert.DeserializeObject<EmbedClass>(embedQuerString.ToString());
        var embedQuery = embedClass.embedQuerString;
        // Add user email for authentication
        embedQuery += "&embed_user_email=" + GlobalAppSettings.EmbedDetails.UserEmail;
        // Add server timestamp to handle timezone differences
        double timeStamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
        embedQuery += "&embed_server_timestamp=" + timeStamp;
        var embedDetailsUrl = "/embed/authorize?" + embedQuery + "&embed_signature=" + GetSignatureUrl(embedQuery);
    
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(embedClass.dashboardServerApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            var result = client.GetAsync(embedClass.dashboardServerApiUrl + embedDetailsUrl).Result;
            string resultContent = result.Content.ReadAsStringAsync().Result;
            return resultContent;
        }
    }
    
  4. Invoke Authorization Server
    The authorization server returns a JSON response containing the embed token and its expiration time. Store the token globally for reuse. For multi-tab dashboards, check for an array of tokens in the response.
    Example JavaScript code to process the response:

    function sendAuthorizationRequest(payload, dashboardId) {
        $.ajax({
            url: authorizationServerUrl,
            type: "POST",
            async: true,
            data: JSON.stringify(payload),
            contentType: "application/json",
            success: function (response) {
                try {
                    const parsed = typeof response === 'string' ? JSON.parse(response) : response;
                    let accessToken, expires;
                    let isMultiTab = false;
    
                    if (Array.isArray(parsed?.Data)) { // For multi-tab dashboard
                        for (const item of parsed.Data) {
                            if (item.access_token) {
                                accessToken = item.access_token;
                                isMultiTab = true;
                                expires = item[".expires"];
                                break;
                            }
                        }
                    } else {
                        accessToken = parsed.Data.access_token;
                        expires = parsed.Data[".expires"];
                    }
    
                    if (accessToken) {
                        token = accessToken;
                        tokenExpiry = new Date(expires);
                        renderDashboard(dashboardId);
                    } else {
                        alert("Access token not found in response.");
                    }
                } catch (error) {
                    alert("Error parsing response: " + error);
                }
            },
        });
    }
    

How to Embed a Dashboard Using the Embed Token

Once the embed token is generated, use it to render the dashboard in your application with the Bold BI JavaScript SDK to create and load the dashboard. Pass the embed token, dashboard ID, server URL, and container ID. For multi-tab dashboards, set isMultiTabDashboard to true.
Example JavaScript code to render the dashboard:

function renderDashboard(dashboardId) {
    if (!token || isTokenExpired()) {
        console.log("Token expired or missing. Fetching new token...");
        getDashboardAccessToken(dashboardId, 'view', '100000');
        return;
    }
    this.dashboard = BoldBI.create({
        serverUrl: rootUrl + "/" + siteIdentifier,
        dashboardId: dashboardId,
        embedContainerId: "dashboard",
        embedToken: token,
        isMultiTabDashboard: isMultiTab
    });
    this.dashboard.loadDashboard();
}

function isTokenExpired() {
    if (!tokenExpiry) return true;
    return new Date() >= new Date(tokenExpiry);
}

Reuse the Embed Token

The embed token can be reused for multiple dashboard loads until it expires. This supports:

  • Row-level security (RLS)
  • Group-based authorization
  • Anonymous user access

Supported Scenarios with Embed Token

  • For Bold BI users:
    • Dashboard viewer
    • Dashboard designer
    • Multi-tab dashboard
  • For anonymous users:
    • Dashboard viewer

Note: To render a multi-tab dashboard, set the isMultiTabDashboard property to true when embedding the dashboard using the Bold BI JavaScript SDK.

Sample Reference

The ASP.NET Core sample on GitHub includes detailed instructions for running the sample in the README.md file.

Was this article useful?
Like
Dislike
Help us improve this page
Please provide feedback or comments
DV
Written by Dharshini Vivekanandan
Updated:
Comments (0)
Please  to leave a comment
Access denied
Access denied