Features
Identity Verification
Identify signed-in website users with a server-signed JWT and connect their verified profile to MuChat.
Identity verification connects a user who is signed in to your website with their MuChat conversation. Your server signs a JSON Web Token (JWT); the widget sends it to MuChat to verify the user and load the corresponding conversation and profile.
MuChat uses HS256 JWTs and a signing key belonging to the widget channel. The website token in the installation code is public and is different from this secret.
When to Use Identity Verification
Send the user's verified name or email so MuChat can use them in its replies.
Use a stable user_id from your own account system. Identifying the same account in the same widget channel lets MuChat resolve its conversation without relying solely on the browser's guest cookie.
Enable Allow access only to authenticated users after implementing identification. The bubble and chat remain hidden until the current page identifies a user successfully, including when a verified session was restored.
Implementation Guide
Prerequisites
Get Your Secret Key
Open the installation panel
In the dashboard, open your agent, go to Deploy, and click Manage on Chat Widget. Open Deploy above the preview and choose Website widget.
Open Identity verification
Expand Identity verification. Copy the Secret key with its copy button. If no key exists, use Show to create it.
Store the key on your server
Save it as MUCHAT_IDENTITY_SECRET in your server environment. Keep it out of client bundles, public environment variables, source control, and URLs.
JWT Implementation
JWT Overview
A JWT contains a header, claims, and a signature. MuChat verifies the signature with this widget channel's key before accepting the identity. It does not encrypt the payload: anyone holding a token can read its contents.
Generating the JWT Payload
{
"user_id": "user-123",
"name": "User",
"email": "user@example.com",
"iat": 1792886400,
"exp": 1792890000
}Use an immutable account ID, rather than an email address that can change. Optional claims must use the supported names; arbitrary top-level fields and user_metadata are rejected.
Sign the Token on Your Server
Install jsonwebtoken in your server application. Call this helper with the user resolved from your authenticated server session.
import jwt from "jsonwebtoken";
export function createUserToken(user) {
const secret = process.env.MUCHAT_IDENTITY_SECRET;
if (!secret) throw new Error("Missing identity secret");
return jwt.sign(
{
user_id: String(user.id),
name: user.name,
email: user.email
},
secret,
{ algorithm: "HS256", expiresIn: "1h" }
);
}Install PyJWT in your server application. Here user is your authenticated account record.
import os
import time
import jwt
def create_user_token(user):
now = int(time.time())
return jwt.encode(
{
"user_id": str(user.id),
"name": user.name,
"email": user.email,
"iat": now,
"exp": now + 3600,
},
os.environ["MUCHAT_IDENTITY_SECRET"],
algorithm="HS256",
)Install firebase/php-jwt with Composer. Pass the account resolved from your server session to this function.
<?php
use Firebase\JWT\JWT;
function createUserToken(array $user): string {
$secret = getenv('MUCHAT_IDENTITY_SECRET');
if (!$secret) {
throw new RuntimeException('Missing identity secret');
}
$now = time();
return JWT::encode([
'user_id' => (string) $user['id'],
'name' => $user['name'],
'email' => $user['email'],
'iat' => $now,
'exp' => $now + 3600,
], $secret, 'HS256');
}Identifying the User
After window.muchatSDK.run(...) has initialized the SDK, get the token from your server and pass it as a string:
async function identifyMuchatUser() {
const response = await fetch("/api/muchat/token", {
credentials: "same-origin",
cache: "no-store"
});
if (!response.ok) throw new Error("Could not get user token");
const { token } = await response.json();
window.$muchat.setUser(token);
}
identifyMuchatUser().catch(console.error);/api/muchat/token is an endpoint you implement in your application. It is not a MuChat API endpoint. setUser queues the token if the widget is still bootstrapping; its return value is not a promise or proof of successful verification.
When authenticated-only access is enabled, muchat:user-identified fires after successful identification. Listen before calling setUser. In an unrestricted widget, this event is not emitted; inspect the identify request in the browser's Network panel when testing. Errors are reported through muchat:error.
Logging out Users
MuChat has no public logout() method. reset() is ignored for verified users, and destroy() removes the widget without deleting its session cookie.
During your application's logout flow, destroy the widget and remove its cookie before mounting a guest widget or reloading the page:
async function disconnectMuchatUser(websiteToken) {
await window.$muchat.destroy();
const name = encodeURIComponent(`mu_conversation_${websiteToken}`);
const expired = `${name}=; Max-Age=0; Path=/`;
document.cookie = expired;
const domain = window.muchatSettings?.baseDomain;
if (domain) document.cookie = `${expired}; Domain=${domain}`;
}Pass the websiteToken from the installation code. Complete your application's own logout and reload or initialize the widget for the new authentication state. Identify the new account before allowing it to use authenticated chat. Do not treat closing or hiding the widget as logout.
How Contact Updates Work
The token's profile fields are processed during identification. Omitted fields do not request an update; null profile values are ignored in this flow. A newly signed token can supply updated values, but a higher-trust manual profile edit may take precedence in the merged contact record.
Verified AI context uses the signed claims from the current channel connection. It does not automatically expose every field in the merged contact record. To update a profile, issue a new token and call setUser again; avoid simultaneous calls with different tokens.
Complete JWT Implementation Flow
Generate the token for the signed-in account
Your application authenticates the request, loads the account from its session, and calls the signing helper. Return { "token": "..." } with Cache-Control: private, no-store. Return an unauthorized response for a guest; do not issue a token for an arbitrary ID from query parameters.
Identify the user in the frontend
Initialize the widget once, fetch the token, and call setUser(token). Repeat this on a full page load. For account changes in a single-page app, finish the old widget's teardown before initializing and identifying the new account.
Check access and continuity
Test the same account in a second browser, a different account, an expired token, and logout on a shared device. If you enable authenticated-only access, confirm that guests cannot open the chat and a restored session waits for identification on the new page.
Identity Parameters
| Claim | Type | Behavior |
|---|---|---|
user_id | string | Required, stable account ID, up to 512 characters |
name, first_name, last_name | string | Optional profile names |
email | string | Optional valid email address |
phone_number | string | Optional phone number in international format |
locale, country_code | string | Optional profile locale and two-character country code |
exp, iat, nbf | integer | Optional Unix timestamps in seconds; validated when present |
iss | string | Optional issuer; changes the identity key to iss:user_id, so keep it stable |
aud | string or string[] | If supplied, must include this widget's agent ID |
sub, jti | string | Optional standard claims; neither replaces user_id |
Do not include internal fields such as identifier or avatar_blob_id.
Security & Best Practices
Keep the signing secret on your server and send only the current user's short-lived token over HTTPS. JWT payloads are readable; include only the profile data the conversation needs. Do not log tokens.
Use Rotate in Identity verification, then update your server secret. The previous key remains valid for a 24-hour transition period unless revoked earlier. If you set the optional kid header, update it to the new key ID as well. Key rotation does not by itself log out every existing widget session.
A verified identity does not give every custom action access to an account. Your API must still check ownership and permissions for each protected operation. Never authorize access solely from an account ID typed in chat.
Troubleshooting
Check HS256, the secret for the same widget channel, a string user_id, and current exp, iat, and nbf values. Check optional aud and kid, and remove unsupported top-level claims. WIDGET_IDENTITY_INVALID indicates an invalid identity token.
With authenticated-only access on, initialization alone is insufficient. Fetch the current user's token and identify them on this page. Register error and identification listeners before sending the token; also check that the channel and bubble are enabled.
Review logout and account switching. Await destroy(), clear the cookie for this website token and configured domain, then initialize and identify the current account. Do not reuse a cached token across accounts or assume reset() signs out a verified user.