Sharing Secrets
Sharing secrets are available on the Business plan (see Plans Comparison).
A sharing secret is a JWT that your server signs with your organization's
Embed Secret and adds to a sharing link as the
sharingSecret URL parameter. A link with
Require Sharing Secret turned on opens only with a valid,
unexpired one, and what is in it decides what the viewer sees: which filter values they are
limited to and which reports are hidden. Anyone can decode a JWT and read its claims, but changing
them breaks the signature, and only your server holds the Embed Secret that makes a new one.
Creating Sharing Secrets
Your server needs two things: the link's sharing token, which is the sharingToken parameter in its
URL, and the Embed Secret. Keep the Embed Secret on the server, in an environment variable, and
never send it to the browser. Sign with HS256; HS384 and HS512 are accepted as well.
- Ruby
- Node.js
- Go
- Python
- PHP
- Java
- Rust
# Uses jwt gem (https://github.com/jwt/ruby-jwt) to generate the JWT token.
# Install via 'gem install jwt' or add to your Gemfile.
require 'jwt'
# The sharing link that we are working with
base_url = 'https://dashboards.cluvio.com/dashboards/wm73-peg8-y0qv/shared?sharingToken=fc77dd26-1b9d-417d-9489-518bc4ab7431'
sharing_token = 'fc77dd26-1b9d-417d-9489-518bc4ab7431' # sharingToken query parameter from the URL
# Validity (expiration) of the generated token as unix timestamp, should be short.
expires_at = (Time.now + 60 * 60).to_i
# Get your Embed Secret from API Keys & Secrets (https://app.cluvio.com/admin/api-keys).
# Best practice: load it from an environment variable, don't hard-code it.
secret = ENV.fetch('CLUVIO_EMBED_SECRET')
payload = {
sharing_token: sharing_token,
exp: expires_at
}
sharing_secret = JWT.encode(payload, secret)
final_url = "#{base_url}&sharingSecret=#{sharing_secret}"
puts final_url
// Uses jsonwebtoken library (https://github.com/auth0/node-jsonwebtoken) to generate the JWT token.
// Install via 'npm install jsonwebtoken' or add to your package.json
const jwt = require('jsonwebtoken');
// The sharing link that we are working with
const baseUrl = 'https://dashboards.cluvio.com/dashboards/wm73-peg8-y0qv/shared?sharingToken=fc77dd26-1b9d-417d-9489-518bc4ab7431';
const sharingToken = 'fc77dd26-1b9d-417d-9489-518bc4ab7431'; // sharingToken query parameter from the URL
// Validity (expiration) of the generated token as unix timestamp, should be short.
const expiresAt = Math.floor(Date.now() / 1000) + 60 * 60; // valid for 1 hour
// Get your Embed Secret from API Keys & Secrets (https://app.cluvio.com/admin/api-keys).
// Best practice: load it from an environment variable, don't hard-code it.
const secret = process.env.CLUVIO_EMBED_SECRET;
const payload = {
sharing_token: sharingToken,
exp: expiresAt
};
const sharingSecret = jwt.sign(payload, secret);
const finalUrl = `${baseUrl}&sharingSecret=${sharingSecret}`;
console.log(finalUrl);
// Uses golang-jwt (https://github.com/golang-jwt/jwt) to generate the JWT token.
// Run 'go get github.com/golang-jwt/jwt/v5' to install it first.
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
)
func main() {
// The sharing link that we are working with
baseUrl := "https://dashboards.cluvio.com/dashboards/wm73-peg8-y0qv/shared?sharingToken=fc77dd26-1b9d-417d-9489-518bc4ab7431"
sharingToken := "fc77dd26-1b9d-417d-9489-518bc4ab7431" // sharingToken query parameter from the URL
// Validity (expiration) of the generated token as unix timestamp, should be short.
expiresAt := time.Now().Add(time.Hour)
// Get your Embed Secret from API Keys & Secrets (https://app.cluvio.com/admin/api-keys).
// Best practice: load it from an environment variable, don't hard-code it.
secret := os.Getenv("CLUVIO_EMBED_SECRET")
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sharing_token": sharingToken,
"exp": expiresAt.Unix(),
})
// Sign and get the sharingSecret value
sharingSecret, err := token.SignedString([]byte(secret))
if err != nil {
log.Fatal(err)
}
finalUrl := fmt.Sprintf("%s&sharingSecret=%s", baseUrl, sharingSecret)
fmt.Println(finalUrl)
}
# Uses PyJWT (https://github.com/jpadilla/pyjwt) to generate the JWT token.
# Install via 'pip install PyJWT'.
import os
import time
import jwt
# The sharing link that we are working with
base_url = 'https://dashboards.cluvio.com/dashboards/wm73-peg8-y0qv/shared?sharingToken=fc77dd26-1b9d-417d-9489-518bc4ab7431'
sharing_token = 'fc77dd26-1b9d-417d-9489-518bc4ab7431' # sharingToken query parameter from the URL
# Validity (expiration) of the generated token as unix timestamp, should be short.
expires_at = int(time.time()) + 60 * 60
# Get your Embed Secret from API Keys & Secrets (https://app.cluvio.com/admin/api-keys).
# Best practice: load it from an environment variable, don't hard-code it.
secret = os.environ['CLUVIO_EMBED_SECRET']
payload = {
'sharing_token': sharing_token,
'exp': expires_at,
}
sharing_secret = jwt.encode(payload, secret, algorithm='HS256')
final_url = f'{base_url}&sharingSecret={sharing_secret}'
print(final_url)
<?php
// Uses firebase/php-jwt (https://github.com/firebase/php-jwt) to generate the JWT token.
// Install via 'composer require firebase/php-jwt'.
require_once 'vendor/autoload.php';
use Firebase\JWT\JWT;
// The sharing link that we are working with
$base_url = 'https://dashboards.cluvio.com/dashboards/wm73-peg8-y0qv/shared?sharingToken=fc77dd26-1b9d-417d-9489-518bc4ab7431';
$sharing_token = 'fc77dd26-1b9d-417d-9489-518bc4ab7431'; // sharingToken query parameter from the URL
// Validity (expiration) of the generated token as unix timestamp, should be short.
$expires_at = (new DateTimeImmutable('+60 minutes'))->getTimestamp(); // valid for 1 hour
// Get your Embed Secret from API Keys & Secrets (https://app.cluvio.com/admin/api-keys).
// Best practice: load it from an environment variable, don't hard-code it.
$secret = getenv('CLUVIO_EMBED_SECRET');
$payload = [
'sharing_token' => $sharing_token,
'exp' => $expires_at,
];
$sharing_secret = JWT::encode($payload, $secret, 'HS256');
$final_url = "{$base_url}&sharingSecret={$sharing_secret}";
echo $final_url;
// Uses java-jwt library (https://github.com/auth0/java-jwt) to generate the JWT token.
// Install e.g. via maven.
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class JwtExample {
public static void main(String[] args) {
// The sharing link that we are working with
var baseUrl = "https://dashboards.cluvio.com/dashboards/wm73-peg8-y0qv/shared?sharingToken=fc77dd26-1b9d-417d-9489-518bc4ab7431";
var sharingToken = "fc77dd26-1b9d-417d-9489-518bc4ab7431"; // sharingToken query parameter from the URL
// Validity (expiration) of the generated token as unix timestamp, should be short.
var expiresAt = Instant.now().plus(1, ChronoUnit.HOURS);
// Get your Embed Secret from API Keys & Secrets (https://app.cluvio.com/admin/api-keys).
// Best practice: load it from an environment variable, don't hard-code it.
var secret = System.getenv("CLUVIO_EMBED_SECRET");
// Sign and get the sharingSecret value
var sharingSecret = JWT.create()
.withExpiresAt(expiresAt)
.withClaim("sharing_token", sharingToken)
.sign(Algorithm.HMAC256(secret));
var finalUrl = baseUrl + "&sharingSecret=" + sharingSecret;
System.out.println(finalUrl);
}
}
// Uses jsonwebtoken (https://github.com/Keats/jsonwebtoken) library to generate the JWT token.
// Install via cargo as usual.
use std::env;
use std::time::{SystemTime, UNIX_EPOCH};
use serde::Serialize;
use jsonwebtoken::{encode, EncodingKey, Header};
#[derive(Serialize)]
struct Claims {
exp: usize,
sharing_token: String,
}
fn main() {
// The sharing link that we are working with
let base_url = "https://dashboards.cluvio.com/dashboards/wm73-peg8-y0qv/shared?sharingToken=fc77dd26-1b9d-417d-9489-518bc4ab7431";
let sharing_token = "fc77dd26-1b9d-417d-9489-518bc4ab7431"; // sharingToken query parameter from the URL
// Validity (expiration) of the generated token as unix timestamp, should be short.
let exp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as usize + 60 * 60; // 1 hour
// Get your Embed Secret from API Keys & Secrets (https://app.cluvio.com/admin/api-keys).
// Best practice: load it from an environment variable, don't hard-code it.
let secret = env::var("CLUVIO_EMBED_SECRET").expect("CLUVIO_EMBED_SECRET not set");
let claims = Claims { sharing_token: sharing_token.to_owned(), exp };
// Sign and get the sharingSecret value
let sharing_secret = encode(&Header::default(), &claims, &EncodingKey::from_secret(secret.as_ref())).unwrap();
let final_url = format!("{base_url}&sharingSecret={sharing_secret}");
println!("{final_url}");
}
The same code, with your link's URL already in it, is on the link's Info tab under
Sharing Secret (JWT). Put the URL it prints in the
iframe's src, on the page your server renders:
<iframe
src="https://dashboards.cluvio.com/dashboards/wm73-peg8-y0qv/shared?sharingToken=fc77dd26-1b9d-417d-9489-518bc4ab7431&sharingSecret=eyJhbGciOiJIUzI1NiJ9.eyJzaGFyaW5nX3Rva2VuIjoiZmM3N2RkMjYtMWI5ZC00MTdkLTk0ODktNTE4YmM0YWI3NDMxIiwiZXhwIjo0ODMzNDMwNjA0fQ.vbWY6QJNlAxjz0A--aANdCUZuWHWKRLTT5tES__GaqY"
width="100%"
height="600"
frameborder="0"
allowfullscreen
></iframe>
To try a link before your server signs anything, open its Preview tab. It signs a five-minute secret for the preview and renews it as it expires.
Claims
| Claim | Required | What it does |
|---|---|---|
sharing_token | Yes | The link's sharing token. A secret signed for one link does not open another. |
exp | Yes | When the secret expires, as a Unix timestamp in seconds. |
iat | No | When the secret was signed, as a Unix timestamp. Not checked, but the JavaScript library uses it to tell the secret's lifetime. |
fixed_parameters | No | Filter values the viewer is limited to. See Limiting filter values. |
hidden_reports | No | Report IDs to leave off the dashboard. See Hiding reports. |
keep_open_after_expiration | No | true keeps the dashboard on screen after the secret expires, showing the last data it loaded, where it would otherwise show an error. |
data_timestamp | No | A Unix timestamp, as an integer. Reports whose data is older than this run their queries again, even if their refresh interval has not passed yet. Use it when something in your application has just changed the data. A time later than one minute ago counts as one minute ago. |
Keep exp short: between 10 minutes and an hour is usual. A secret that leaks, in a browser history
or a copied URL, stops working when it expires.
A page that stays open longer than that needs a new secret before then. See Updating Sharing Secrets.
Limiting filter values
fixed_parameters maps filter variable names to the values
the viewer may use:
{
"sharing_token": "fc77dd26-1b9d-417d-9489-518bc4ab7431",
"exp": 1798761600,
"fixed_parameters": {
"customer": "4711",
"region": ["EU", "UK"],
"aggregation": "month"
}
}
- One value fixes the filter to it. The viewer can't change it, in the filter bar, in the URL or
with
changeParameters. - A list limits the filter to those values. The viewer chooses among them; a selection with none of them falls back to all of them.
aggregationandtimerange, the built-in filters, take a single string, in the format of Parameters in URLs.
Numbers can be given as strings: "4711" works for a numeric filter as well as 4711.
One dashboard for every customer
To show each signed-in user only their own data, give the dashboard a filter on the column that says which customer a row belongs to, use it in every report's query, and fix it in the sharing secret to the user your server has signed in:
SELECT date_trunc('month', ordered_at) AS month, SUM(total) AS revenue
FROM orders
WHERE {customer_id=customer}
GROUP BY 1
{
"sharing_token": "fc77dd26-1b9d-417d-9489-518bc4ab7431",
"exp": 1798761600,
"fixed_parameters": { "customer": "4711" }
}
Take the customer from your server's own session, never from anything the browser sends with the request. A value the browser sends is a value the viewer can change, and with it they would see another customer's data.
A report that doesn't use the filter isn't limited by it, so check every report on the dashboard. Embed a dashboard scoped per customer walks through the whole setup.
Hiding reports
hidden_reports lists reports to leave off the dashboard for this viewer, by ID. A report's ID is
in the report editor's URL, /reports/<id>/edit. IDs of reports that are not on the link's
dashboards are ignored.
{
"sharing_token": "fc77dd26-1b9d-417d-9489-518bc4ab7431",
"exp": 4833430604,
"hidden_reports": ["8yqp-m4w4-zlx2", "d91g-7p30-zy4q", "1n07-lgly-2mq8", "ywpn-7v62-zqkv"]
}
The sample dashboard at the top of Embedded Analytics, with those four reports hidden:
Updating Sharing Secrets
When a secret expires, the dashboard's next request to Cluvio is refused. The page doesn't need to
reload: send the iframe a new secret with the
updateSharingSecret action, and it carries on
with the new one. Your page gets the new secret from your own server, which signs it the same way
as the first.
There are two moments to do that, and a page that stays open should use both:
- Before the secret expires, on a timer set from its
exp, for example at 80% of its lifetime. The dashboard never sees an expired secret. - When the dashboard sends
secretExpired, after a request was refused. That covers a timer that didn't fire, such as on a laptop that was asleep.
- postMessage
- @cluvio/embed
const frame = document.getElementById('cluvio-dashboard');
let renewalTimer;
// When a secret expires, from its exp claim, in milliseconds
function expiresAt(sharingSecret) {
const payload = sharingSecret.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
return JSON.parse(atob(payload)).exp * 1000;
}
// Renew when 80% of the secret's remaining lifetime has passed. setTimeout fires at once on a
// delay above 2^31 - 1 ms (24.8 days), hence the cap.
function scheduleRenewal(sharingSecret) {
clearTimeout(renewalTimer);
const remaining = expiresAt(sharingSecret) - Date.now();
const delay = Math.min(Math.max(0, remaining * 0.8), 2 ** 31 - 1);
renewalTimer = setTimeout(renewSharingSecret, delay);
}
async function renewSharingSecret() {
// Your own endpoint, which signs a new secret for the signed-in user
const response = await fetch('/cluvio/sharing-secret', { method: 'POST' });
const { sharingSecret } = await response.json();
frame.contentWindow.postMessage(
JSON.stringify({ action: 'updateSharingSecret', params: { sharingSecret } }),
'https://dashboards.cluvio.com'
);
scheduleRenewal(sharingSecret);
}
// Before it expires: on a timer, starting from the secret the page was served with
scheduleRenewal(new URL(frame.src).searchParams.get('sharingSecret'));
// After it expired: when the dashboard says a request was refused
window.addEventListener('message', (event) => {
if (event.source !== frame.contentWindow || event.origin !== 'https://dashboards.cluvio.com') return;
if (JSON.parse(event.data).event === 'secretExpired') renewSharingSecret();
});
The JavaScript library does both, given a function that fetches the new secret:
import { CluvioEmbed } from '@cluvio/embed';
const embed = await CluvioEmbed.mount({
container: document.getElementById('dashboard'),
dashboardId: 'wm73-peg8-y0qv',
sharingToken: 'fc77dd26-1b9d-417d-9489-518bc4ab7431',
fetchToken: async (signal) => {
// Your own endpoint, which signs a new secret for the signed-in user
const response = await fetch('/cluvio/sharing-secret', { method: 'POST', signal });
return (await response.json()).sharingSecret;
},
});
Include keep_open_after_expiration: true in the secret, so the dashboard stays on screen for the
moment between expiry and the new secret instead of showing an error.
The new secret can carry different fixed_parameters or hidden_reports, so updateSharingSecret
also changes what an open dashboard shows. A drill-down on a link that
viewers can't change is handled that way.
After you reset the Embed Secret, secrets signed with the previous one keep working for 24 hours, so open pages and servers that have not switched yet keep running.