logoSemaphor

Token Options

Options for generating an Auth Token to embed a dashboard

Overview

This section outlines the different options available for generating AuthToken.

AuthToken is a unique, time-sensitive token that secures access to your dashboard. To generate this token, you need to include DASHBOARD_ID and DASHBOARD_SECRET as required fields in the request body, as shown below:

const DASHBOARD_ID = 'd_cf007a8b-19bc-46ad-8787-2915445b7b86'; // Replace with your actual dashboard ID
const DASHBOARD_SECRET = 'ds_f32f0b30-b7e1-40f9-ba6a-9804a5b9d635'; // Replace with your actual dashboard secret
const TOKEN_URL = 'https://semaphor.cloud/api/v1/token';
 

const requestBody = {


  dashboardId: DASHBOARD_ID, 
  dashboardSecret: DASHBOARD_SECRET, 
}; 
 
async function fetchToken() {
  try {
    const response = await fetch(TOKEN_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody),
    });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
 
    const token = await response.json();
    if (token?.accessToken) {
      setAuthToken(token);
    }
  } catch (error) {
    console.error('There was an error!', error);
  }
}

Token Expiry

By default, the AuthToken is valid for 1 hour. However, you can specify a custom expiry time in the request body. Once the token expires, it will no longer be valid, and you will see a "Session expired" message on the dashboard.

The token expiry is specified in seconds. For example, to set the expiry time to 10 minutes, you can pass tokenExpiry: 60 * 10 in the request body.

const requestBody = {
  dashboardId: DASHBOARD_ID,
  dashboardSecret: DASHBOARD_SECRET,
  tokenExpiry: 60 * 10, // 10 minutes //
};

This token will remain valid for 10 minutes. This feature is particularly useful if you want to synchronize your application's session timeout with the dashboard, ensuring a seamless and consistent user experience.

You can also explicitly invalidate the token by calling the invalidateToken function when the user logs out of your application.

import { invalidateToken } from 'semaphor';
 
async function handleLogout() {
  await invalidateToken();
}
 
<button onClick={handleLogout}>Logout</button>;

The invalidateToken function sends a POST request to https://semaphor.cloud/api/v1/invalidate-token to revoke the current session. The request includes the active accessToken in the Authorization header.


User Params

In some instances, you may want to pass user specific information to the dashboard. For example, the currency of the user's region. You can pass this information in the params field in the request body.

const requestBody = {
  dashboardId: DASHBOARD_ID,
  dashboardSecret: DASHBOARD_SECRET,
  params: {

    currencyFormat: {
      locale: 'en-US',
      currency: 'USD',
    },
  },
};

Before rendering the currency for the numbers on the dashboard, Semaphor will first check if the currencyFormat is set in the params field of the AuthToken. If it is, Semaphor will use the currency format specified in the params field. If not, Semaphor will default to the currency format specified in the dashboard settings.

The locale and the currency fields must conform to the Intl.NumberFormat format.

Security Policies

The AuthToken also controls what data user can see in the dashboard. You can set up security policies to restrict the data that a user can access. For more information, see Security & Multi-tenancy section.


Using TokenRequest

When requesting a token from Semaphor API, you can use the TokenRequest type to define the request body and customize your analytics experience.

API Endpoint

POST http://localhost:3000/api/v1/token

Request Body

The request body should match the TokenRequest structure:

/**
 * Parameters for customizing token behavior and formatting.
 */
export type TokenParams = {
  currencyFormat: {
    /**
     * Locale identifier (e.g., 'en-US', 'fr-FR').
     */
    locale: string;
 
    /**
     * Currency code compliant with ISO 4217 (e.g., 'USD', 'EUR').
     */
    currency: string;
  };
};
 
/**
 * Defines a security policy that can be applied at connection or row level.
 */
export type TokenSecurityPolicy = {
  /**
   * Name of the policy (e.g., 'store_sales_primary', 'region_filter').
   */
  name: string;
 
  /**
   * Arbitrary parameters associated with the policy.
   * Examples:
   *
   * // Single value
   * {
   *   tenant: 'tenant_abc_123'
   * }
   *
   * // Multiple values
   * {
   *   state: ['California', 'Nevada', 'Washington']
   * }
   */
  params: {
    [key: string]: string | number | string[] | number[];
  };
};
 
/**
 * UI and behavior configuration for the embedded dashboard.
 */
export type UIConfig = {
  /**
   * Enables self-service editing and lens creation by the end user. Legacy field. Use config.allowEdit instead.
   */
  allowEdit?: boolean;
 
  /**
   * Enables advanced mode features in the dashboard.
   * Defaults to true unless explicitly disabled.
   */
  showAdvancedMode?: boolean;
 
  /**
   * Enables the AI-powered dashboard assistant.
   * Defaults to true unless explicitly disabled.
   */
  showDashboardAssistant?: boolean;
};
 
/**
 * Main payload for generating a secure access token for a dashboard.
 */
export type TokenRequest = {
  /**
   * Identifier of the dashboard to be accessed.
   */
  dashboardId: string;
 
  /**
   * Secret key used for validating access to the dashboard.
   */
  dashboardSecret: string;
 
  /**
   * Token expiry duration in seconds.
   */
  tokenExpiry?: number;
 
  /**
   * Unique identifier of the tenant.
   */
  tenantId?: string;
 
  /**
   * Unique identifier of the end user accessing the dashboard.
   */
  endUserId?: string;
 
  /**
   * Email of the end user (for personalization, audit, or identification).
   */
  endUserEmail?: string;
 
  /**
   * Enables self-service editing and lens creation by the end user.
   */
  allowEdit?: boolean;
 
  /**
   * Connection-level security policies.
   * Can be a single policy or an array of policies.
   */
  cls?: TokenSecurityPolicy[] | TokenSecurityPolicy;
 
  /**
   * Row-level security policies.
   * Can be a single policy or an array of policies.
   */
  rcls?: TokenSecurityPolicy[] | TokenSecurityPolicy;
 
  /**
   * Parameter overrides and preferences (e.g., formatting).
   */
  params?: TokenParams;
 
  /**
   * UI behavior and feature flags.
   */
  config?: UIConfig;
};

On this page