# Identity Verification > Sign your users in to the chat the same way they're signed in to your website Identity verification tells your agent which of your users it's talking to. When someone is signed in to your website or app, your server signs a short-lived token for them, and the Chat bubble passes it to QwryAI. QwryAI checks the signature, links the conversation to that user's contact and gives the agent their details. QwryAI verifies identity with a JSON Web Token (JWT) signed with your agent's secret key. Because only your server knows the key, a visitor can't pretend to be someone else by editing your page's JavaScript. ## When to Use Identity Verification > [accordion] Personalize the Chat Experience > > When the user is verified, the agent can: > > * Greet them by name instead of a generic "Hi there" > * Use their email and other details without asking for them again > * Tailor answers to details you add to the token, such as their plan > * Keep their conversation history with them across devices > [accordion] Enable Actions with User Data > > [Client-side custom Actions](/docs/developer-guides/website-integration/client-side-custom-actions) receive the signed-in user's ID, so your code can look up their orders or account without asking them who they are. > > > [!NOTE] > > > > On Shopify stores installed from **Deploy › Shopify**, QwryAI signs in logged-in customers for you. You don't need this guide there. > [accordion] Sync Contacts with the Agent > > The email, name and phone you put in the token update the user's contact in QwryAI every time they're identified, so your contact list stays current without a separate import. ## Implementation Guide ### Prerequisites > [!NOTE] > > A website with the QwryAI Chat bubble already installed and working. New to QwryAI? Start with [Your first AI agent](/docs/user-guides/quick-start/your-first-agent). ### Get Your Secret Key **1. Open your agent** Sign in and open the agent you've deployed. **2. Open the Website bubble sheet** Open **Channels**, select **Manage** on the **Chat bubble** card, then open **Deploy** and choose **Website widget**. **3. Copy the secret key** Scroll to **Identity verification**. The **Secret key** is shown masked; select the copy icon beside it to copy the full key. QwryAI creates the key the first time this sheet opens. ![The Identity verification section of the Website bubble sheet, with the masked Secret key, its copy icon, the Rotate button, the warning Keep your secret key safe, and the identity verification code sample.](annotated/01-identity-secret.webp "Website bubble › Identity verification.") Store the key on your server as an environment variable, such as `QWRYAI_IDENTITY_SECRET`. > [!WARNING] > > Keep your secret key on your server. Never commit it to your repository or put it in code that runs in the browser. **Rotate** replaces the key. Tokens signed with the old key stop working straight away, and signed-in visitors aren't identified again until your server signs with the new one. ## Method 1: JWT #### JWT Overview A JSON Web Token carries the user's details, signed with your secret key. Sending it does two things: it **identifies the user** to the agent, and it **creates or updates their contact** in QwryAI. #### Generating the JWT Payload Sign the token on your server with the **HS256** algorithm. > [!NOTE] > > `user_id` and an expiry (`exp`) are required. QwryAI refuses a token without `user_id`, or one that never expires. Every other claim is optional. | Claim | Type | Description | | - | - | - | | `user_id` | string or number | **Required.** Your user's stable ID. QwryAI links the visitor to the contact with this ID. | | `exp` | number | **Required.** When the token expires. `expiresIn: '1h'` sets it for you. | | `email` | string | The user's email address. | | `name` | string | The user's full name. | | `phone` | string | The user's phone number. | | any other claim | string, number, boolean | Extra details, such as `plan` or `company`. QwryAI saves each one on the contact when your workspace has a contact attribute with the same key. | > [tab] Node.js > > ```javascript > const jwt = require("jsonwebtoken"); > > // Run this on your server and send the returned token to your page. > function generateQwryaiToken(user) { > const secret = process.env.QWRYAI_IDENTITY_SECRET; > > return jwt.sign( > { > user_id: user.id, // required > email: user.email, > name: user.name, > phone: user.phone, // e.g. "+15551234567" > plan: user.plan, // an extra detail > }, > secret, > { algorithm: "HS256", expiresIn: "1h" } > ); > } > ``` > [tab] Python > > ```python > import os > import time > import jwt # pip install PyJWT > > # Run this on your server and send the returned token to your page. > def generate_qwryai_token(user): > secret = os.environ["QWRYAI_IDENTITY_SECRET"] > payload = { > "user_id": user.id, # required > "email": user.email, > "name": user.name, > "phone": user.phone, > "plan": user.plan, # an extra detail > "exp": int(time.time()) + 60 * 60, # required: 1 hour > } > return jwt.encode(payload, secret, algorithm="HS256") > ``` > [!TIP] > > The **Identity verification** section of the Website bubble sheet has the same Node.js sample, ready to copy. For a login endpoint that returns the token and the page code that uses it, see [Complete JWT Implementation Flow](#complete-jwt-implementation-flow). #### Identifying the User Once your page has the token, pass it to the Chat bubble with `identify`: ```javascript // Get the signed token from your server const token = await getQwryaiToken(); // When the user is signed in: on page load and right after they sign in window.qwryai("identify", { token }); ``` You can call it straight after the embed snippet. Until the chat loads, the token waits, and QwryAI checks it when the chat loads. If the check fails, the visitor stays anonymous. Once the chat has loaded, the promise `identify` returns resolves with the user's contact, or rejects with the reason the token was refused, and the `contactIdentified` [event](/docs/developer-guides/website-integration/chatbot-event-listeners) fires on success. > [!WARNING] > > `identify` takes only the token. Put everything you want QwryAI to know inside the signed token, never next to it. #### Logging out Users When the user signs out of your site, clear them from the chat: ```javascript window.qwryai("logout"); ``` The next visitor on that device starts as a new, anonymous visitor. To also show the welcome popup again, call `window.qwryai("reset")` instead. #### How Contact Updates Work * **Adding and updating:** the email, name and phone in each token update the contact. A claim you leave out keeps its current value. * **Extra details:** extra claims are saved on the contact only when your workspace has a contact attribute with that exact key. Others are ignored. * **What the agent sees:** the agent sees the contact's name, email, phone, user ID and saved attributes, and can use them in its answers. ## Complete JWT Implementation Flow ### Step 1: Generate the token on your server Add an endpoint that only answers signed-in users and returns a fresh token. > [tab] Node.js (Express) > > ```javascript > const express = require("express"); > const jwt = require("jsonwebtoken"); > > const app = express(); > > // GET /api/qwryai-token: only for signed-in users > app.get("/api/qwryai-token", requireLogin, (req, res) => { > const user = req.user; > const token = jwt.sign( > { user_id: user.id, email: user.email, name: user.name, plan: user.plan }, > process.env.QWRYAI_IDENTITY_SECRET, > { algorithm: "HS256", expiresIn: "1h" } > ); > res.json({ token }); > }); > ``` > [tab] Python (Flask) > > ```python > import os, time > import jwt > from flask import Flask, jsonify > from flask_login import login_required, current_user > > app = Flask(__name__) > > @app.get("/api/qwryai-token") > @login_required > def qwryai_token(): > token = jwt.encode( > { > "user_id": str(current_user.id), > "email": current_user.email, > "name": current_user.name, > "exp": int(time.time()) + 3600, > }, > os.environ["QWRYAI_IDENTITY_SECRET"], > algorithm="HS256", > ) > return jsonify(token=token) > ``` ### Step 2: Identify the user in your page Add this after the embed snippet, on every page: ```javascript async function identifyQwryaiUser() { const response = await fetch("/api/qwryai-token", { credentials: "include" }); if (!response.ok) return; // not signed in: the visitor stays anonymous const { token } = await response.json(); await window.qwryai("identify", { token }); } identifyQwryaiUser(); // Call it again right after sign-in, and on sign-out: // window.qwryai("logout"); ``` To check it worked, sign in, open the chat and ask "Who am I?". The agent should answer with your name. ## Identity Parameters | Call | Parameters | Description | | - | - | - | | `window.qwryai("identify", { token })` | `token`: the JWT your server signed | Verifies the user and updates their contact. Returns a promise that resolves with the contact once the chat has loaded. | | `window.qwryai("logout")` | none | Clears the signed-in user. The visitor starts over as a new one. | | `window.qwryai("reset")` | none | Like `logout`, and also shows the welcome popup again. | > [!NOTE] > > For details that don't need verifying, such as a newsletter sign-up's email, `window.qwryai("setUser", { email, name })` names the visitor without a token. It needs an `email`, `externalUserId` or `accountId`. Treat these details as unverified: anyone can set them from the browser. ## Security & Best Practices > [accordion] Sign Tokens on the Server > > * Create tokens only on your server, never in the browser. > * Keep the secret key in an environment variable or secrets manager. > * Rotate the key with **Rotate** if you think it has leaked, then deploy the new key. > [accordion] User ID Format > > * Use a stable, unique ID that never changes for that user, such as your database ID. > * Avoid email addresses as IDs: people change them. > [accordion] Extra Details > > * Put only what the agent should know in the token. Everything you add can reach the agent's context. > * Use string, number or boolean values. Objects and lists are ignored. > [accordion] JWT Security > > * Keep tokens short-lived: an hour is plenty, and you can fetch a new one on each page load. > * Use HS256: QwryAI refuses other algorithms. > * Serve your site over HTTPS so tokens can't be read in transit. ## Troubleshooting > [accordion] The user isn't identified > > Catch the promise `identify` returns, or check the browser console, to see why. Common causes: > > * **The signature doesn't match:** the token was signed with an old or wrong key. Copy the key again from **Identity verification**. > * **The token must include user_id:** add a `user_id` claim. > * **The token must expire:** add `exp`, or `expiresIn` in your JWT library. > * **The token expired:** fetch a fresh token instead of reusing an old one. > [accordion] Extra details aren't saved > > Only claims whose key matches one of your workspace's contact attributes are saved. Check the spelling and case of the claim's key. > [accordion] The identity doesn't persist > > Call `identify` on every page load while the user is signed in, not only right after sign-in, and make sure nothing calls `logout` on page load. > [accordion] A previous user's chat shows up > > Call `window.qwryai("logout")` when a user signs out, especially on shared devices. ## Next Steps > [card] Client-Side Custom Actions | /docs/developer-guides/website-integration/client-side-custom-actions | Use the signed-in user's ID in your own Actions. > [card] Client-Side Custom Forms | /docs/developer-guides/website-integration/client-side-custom-forms | Show your own forms inside the chat. > [card] Contacts | /docs/user-guides/chatbot/contacts/contacts-overview | See who your verified users are and what they've asked. > [card] Event Listeners | /docs/developer-guides/website-integration/chatbot-event-listeners | Know when a user has been identified with contactIdentified.