> For the complete documentation index, see [llms.txt](https://docs-v3.toucantoco.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-v3.toucantoco.com/visualizations-and-layouts/embedding/authentication.md).

# Authentication

To embed a Story, Tile, or Dashboard Builder within your environment, you’ll need to authenticate each embed. Our authentication system is designed to be both secure and flexible. Without duplicating your user database in Toucan, you can pass a user context that dynamically segments data.

## Overview

<figure><img src="/files/EV1btzZDRlffBApYpBAa" alt=""><figcaption></figcaption></figure>

The authentication flow uses the **Authorization Grant Flow**. Using a combination of credentials and a signed payload (the JWT), Toucan is able to authenticate your embeds and securely handle the embed context.

## Embed Manager

**Embed Manager Interface**\
The admin interface allows you to manage embeds and set up authentication.\
Path: `Admin Area > Embed Manager > Embed Settings`

<figure><img src="/files/x5I3LiHuBC3QEde3Ppj1" alt=""><figcaption><p>Access Embed Manager from Admin Area</p></figcaption></figure>

<figure><img src="/files/Q4oQTbwIDId9Zk7MsgCa" alt=""><figcaption><p>Embed Settings</p></figcaption></figure>

## Generate your client secret

Generate a client secret by clicking "Re-generate secret" in the Embed Manager.

{% hint style="warning" %}
Once generated, copy and store it securely, as it will disappear upon refreshing the page.
{% endhint %}

<figure><img src="/files/ZVga5cxxByviAABD2qJh" alt=""><figcaption></figcaption></figure>

## Cryptographic keys

You have two methods to manage authentication tokens securely:

1. **RSA Key Pair Management:**

   Generate and manage a single RSA key pair to sign payloads with the private key.\
   Recommended key strength: at least 2048 bits (in this example, we use 4096 bits).

   ```bash
   # Generate a private key
   openssl genrsa -out "toucan_priv.pem" 4096

   # Generate a public key
   openssl rsa -in "toucan_priv.pem" -pubout -out "toucan_pub.pem"
   ```

   Once generated, upload the public key to your Toucan admin area.

   Uploading another public key will deny the old signed JWTs.
2. **Using a JWKS Endpoint:**

   If you wish to host the public keys yourself, you can use a [JWKS](https://auth0.com/docs/secure/tokens/json-web-tokens/json-web-key-sets) endpoint.

   This option allows you to specify multiple public keys, enabling you to rotate keys for enhanced security

<figure><img src="/files/x4DeZHmADdZrya7i5MT0" alt=""><figcaption><p>JWKS method</p></figcaption></figure>

## Create JWT tokens with user context

To properly initiates the embed, you need to send the **embed context** and fetch an **opaque token** (an access token with limited information). To assure integrity and authenticity, the embed context is signed with a private key. The signed payload is called a **JWT assertion**.

This exchange of JWT should be done on the server side to avoid leaking your private key and client secret to the client.

Here's an example of how to sign an embed context with a private key:

**Code example in JS**

{% code overflow="wrap" lineNumbers="true" %}

```javascript
const fs = require('fs')
const jwt = require('jsonwebtoken')
​
​
const privateKey = fs.readFileSync('PATH_TO_YOUR_TOUCAN_EMBED_PRIVATE_RSA_KEY', 'utf8')
​
function signToken(payload) {
  try {
    return jwt.sign(payload, privateKey, { algorithm: 'RS512' });
  } catch (err) {
    throw err
  }
}
​
const token = signToken({
  sub: "toucan-embed-client",
  iss: "https://<YOUR TENANT ID>-embed",
  aud: "https://<YOUR INSTANCE URL>/api/auth/realms/<YOUR TENANT ID>",
  exp: <TIMESTAMP_IN_FUTURE>,
  jti: "<RANDOM_UNIQUE_ID>",
  embed_context: {
    "username": "YOUR_USER_EMAIL", // MANDATORY : user id
    "workspace_id": "WORKSPACE_ID", // MANDATORY : workspace id
    "roles": ["USER"],  // MANDATORY
    "privileges": {  // MANDATORY : user access's right
      "APP-ID": ["PRIVILEGE"], // PRIVILEGE like "view", "validate" and "contibute"
    },
    "groups": ["USER_GROUP"],  // user group
    "attributes": {  // everything else you want that can be used for custom permission, queries...
      "ENTITY_ID": "ENTITY_ID"
    },
    "secrets": { // Secrets will not be sent to the front or displayed, allowing data such as credentials or tokens used for authentication to be sent.
      "TOKEN": "ACCESS_TOKEN_FOR_DATAWAREHOUSE"
    }
  }
})
```

{% endcode %}

{% hint style="info" %}
Other code examples lie in your **Embed Settings** interface.
{% endhint %}

**JWT Token's payload**

* **sub**: subject of the JWT. Shared in your Embed Interface settings.
* **iss**: issuer of the JWT. Shared in your Embed Interface settings.
* **aud**: recipient for which the JWT is intended. Shared in your Embed Interface settings.
* **exp**: time after which the JWT expires, in timestamp. Should follow your own authentication expiration policy.
* **jti:** unique identifier; can be used to prevent the JWT from being replayed. You have to generate a random string.
* **embed\_context**: object that represents the user and his context. Let's dive in.
  * **username**: it will represent your user. We recommend using the user's email but you could also use a unique identifier.
  * **workspace\_id**: the workspace ID where the user is. The embed manager should show its value in the example.
  * **roles**: USER or ADMIN. For your users, we recommend to let USER. For your SDK Key, for instance, ADMIN should be used. (cf. authenticate Embed SDK)
  * **privileges:** object that describes your user access's right to apps.
    * keys are Apps' IDs (cf. [find Apps' IDs](/visualizations-and-layouts/apps/managing-apps/creating-apps.md#find-app-id))
    * value is an enum on \["view", "validator", "contribute"] (more information in [user management](/administration/managing-users/users.md#create-users) section)
  * **groups:** user groups defined in Toucan. Can be useful to define [visibility rules](/administration/managing-users/setting-up-permissions-and-visibilities.md) based on user groups.
  * **attributes:** arbitrary variables that give additional context to the user. Most of the time, it includes information that allows data segregation on Live Data implementation.
  * **secrets**: variables used to send data to the Toucan tenant that will not be displayed. This section is used for variables that must remain secret, such as passwords or tokens.

{% hint style="warning" %}
**Warning**

As of today, we can't support a user context bigger than **3.5KB.** Toucan won't raise an error if it exceeds it, it will truncate it. If you encounter odd issues, please use the "**Check token**" in **Embed Settings** to ensure that your user's context is complete and not truncated.
{% endhint %}

## Generating the Opaque Token

To fetch an opaque token, use the JWT assertion crafted earlier. This token is opaque because it does not contain sensitive information.

**Curl example**

```bash
curl --request POST -u "toucan-embed-client:<CLIENT_SECRET>"
  --url https://<YOUR INSTANCE URL>/api/auth/realms/<YOUR TENANT ID>/protocol/openid-connect/token \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \
  --data scope=embed \
  --data assertion=<JWT_TOKEN>
```

**Parameters**

* **CLIENT\_SECRET:** string retrieve after uploading your public key
* **OAUTH\_SERVER\_URL:** URL of our own authentication service. Shared in the Embed Settings interface.
* **TENANT\_ID:** id of your tenant. Shared in the Embed Settings interface.
* **JWT\_TOKEN:** token that represents your user, crafted in the previous step.

{% hint style="success" %}
Once your opaque token is generated, pass it to the embed script in your application.
{% endhint %}

**Example**

**Static insertion**

{% code overflow="wrap" %}

```html
<script
  async
  src="https://myinstance.toucantoco.com/scripts/embedLauncher.js?id={EMBED_ID}&token=eyJ..."
  type="text/javascript"
></script>
```

{% endcode %}

with `eyJ...` being your opaque token.

**Programmatic insertion**

*(cf.* [*Embed SDK*](/visualizations-and-layouts/embedding/embed-sdk.md#insertembedbyid) *and* [*Embed SDK Authentication*](/visualizations-and-layouts/embedding/embed-sdk/embed-sdk-authentication.md)*)*

* **SDK\_AUTH\_TOKEN:** A token generated with admin rights to access all your embeds
* **EMBED\_ID: C**an be found in the Dashboards tab of your apps, or directly in the Embed Manager.

```javascript
const instance = await TcTcEmbed.initialize('SDK_AUTH_TOKEN');

await instance.insertEmbedById(
    'MY_EMBED_ID',
    document.getElementById('parent-container'),
    {
        token: 'eyJ...',
        ...
    }
);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs-v3.toucantoco.com/visualizations-and-layouts/embedding/authentication.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
