Freshchat enables you to manage user authentication through JSON Web Token (JWT). With JWT user authentication, you can allow only authenticated users to initiate conversations via your configured Web widgets.
This article provides information about the JWT user authentication for Freshchat Web Chat widgets.
The article contains |
Overview
When you enforce user authentication for Web Chat widgets, JWT token authentication becomes mandatory for both logged-in and anonymous users. This ensures that all interactions, whether from registered users or visitors, are secured through token verification.
JWT User authentication workflow for Web Chat widgets
- Conversation Initiation: A user clicks on a chat widget to start a conversation.
- Token Request: Freshchat requests a signed JWT token that includes user data.
- Chat Initialization: Freshchat initializes the chat session by passing the JWT token.
- Token Verification: Freshchat receives the user details from the JWT payload and grants the user access to the chat session.
Enforce user authentication
Note: If JWT user authentication is configured and enabled, it becomes mandatory for both visitors and identified users. This ensures that all interactions, whether from anonymous visitors or authenticated users, require secure token verification.
- Log in to your account as an admin.
- Go to Admin Settings > Channels > Web Chat. Click on the User authentication tab.
- Add Encryption key
- Click Generate Key to create a new encryption key. This is a one-time process.
- Copy and save the encryption key as you'll need it to generate JWT tokens after enabling user authentication.
Note: The generated key is valid and the same for all configured widgets in your account.
- Enforce user authentication: Toggle the option to enable JWT user authentication. A confirmation pop-up will appear. Click Enforce to confirm.
- Once JWT authentication is enforced, it is mandatory to pass JWT token for all users using the web widget. You can also see that your user authentication is Active.
- You can disable the JWT user authentication at any time.
Click on the toggle to disable user authentication and then click Disable on the pop-up that appears.
Once disabled, the "Active" label will disappear, and the draft help text will appear again under the encrypted key section.
Note: This action will disable user authentication for all Web Chat widgets.
Generate a JWT token
JWT is an open standard (RFC 7519) URL-safe token used for securely transferring information between parties. For example, after enforcing user authentication, a JWT token will be required each time a user starts a conversation via Web Chat widgets.
Note: You don't need to manually create JWT tokens. You can use one of the available JWT libraries in languages such as Node.js, Ruby, or Python. Alternatively, you can use jwt.io to generate tokens through a web-based form. However, it is recommended to avoid exposing JWT tokens to third-party sites. If you are unsure about generating JWT tokens, contact your Engineering or Support teams for assistance.
Components of a JWT Token
A JWT comprises the three main parts:
- Header
- Payload
- Signature
Header
Specifies the type of token and the signing algorithm used. It includes two fields:
alg: The algorithm used to sign the token. For example, HS256 for Freshchat.
typ: The type of token, which is JWT.
Example:
{ "alg": "HS256", "typ": "JWT" }
Payload
Contains the claims or data you wish to transmit. Here's an example payload with first_name, last_name, phone_number, exp (expiration time), reference_id, and freshchat_uuid.
Note: To authenticate users in Freshchat Web Chat widgets, the only required parameter is freshchat_uuid, which uniquely identifies the user.
{ "first_name": "John", "last_name": "Doe", "phone_number": "+1234567890", "exp": 1716239022, "reference_id": "ref-123456", "freshcat_uuid": "uuid-123456-abcdef" }
- first_name (Optional): The user's first name (e.g., "John"), used to include user-specific information in the payload.
- last_name(Optional): The user's last name (e.g., "Doe"), also used for user identification.
- phone_number (Optional): Stores the user's phone number (e.g., "+1234567890"), which can be used for contact purposes or to facilitate user identification.
- exp (Optional): Defines the expiration time of the token, represented as a Unix timestamp (e.g., 1716239022). This timestamp limits the validity period of the JWT, enhancing security by enforcing timely token renewal.
- Reference_id (Required): A unique identifier for the user within your system (e.g., "ref-123456"). This ID is essential for recognizing and tracking the user accurately across platforms.
- freshcat_uuid (Required): A unique identifier for a user or session in the application's context (e.g., "uuid-123456-abcdef"). Used internally to differentiate between distinct entities or sessions, enabling precise user management and tracking.
Signature
Ensures the token is not altered. It is created by combining the encoded header, payload, and a shared secret using the specified algorithm. You can find your account's shared secret under the User Authentication tab.
The final JWT token is created by combining the encoded header, payload, and signature, concatenated with periods (.).
JWT token = header.payload.signature
Embed the JWT token with Web Chat widget
Once you have enforced JWT user authentication, embed the following script to launch the Web Chat widget with JWT authentication.
<html> <body> <script> window.fcSettings = { onInit: function(){ function authenticateUser(userData) { let authenticateCB = (uuid) => { //debugger; // Signed UUID Hardcoded. Call Customer backend and generate the signed uuid from uuid let signedUUID = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaGNoYXRfdXVpZCI6IjQ2YjgyZmEzLWJmMDMtNDJmZi1kNWIxLThjZjBkOThiOTRiMSIsIm5hbWUiOiJ0ZXN0In0.NhVeTtOE1tDe2swk18jY13dCbiPUFq8Q1QulT-7IRsSWOboQ4Hw8UBWLiU4K51cc1MTJOZKX5yz-nemHxh8w7i5YJw30lJozptCYIZ1hvV7zacrJZwFu11G4PP8ZMS57p1gn2tquTCyzMpc-U84KzqAOIMEpF2tFisPbplnJeMJsK9s-mn3EW5ZCoAn3x_IsdaLfQszYinVGan74DsNF2og0eEsuJEFRPZWUzgALy01uB9w7xO3jBHUVw1BEGT_YSNOgkLmhiCPO8NONaYbTLAcErqNC2NTCQPRlDke3zWbxHvNswYJIl0QjHRXTZ_sUR44FEfANm7xP3LcDk-NpZg"; window.fcWidget.authenticate(signedUUID); }; if (userData && userData.freshchat_uuid) { authenticateCB(userData.freshchat_uuid); } else { // Generate UUID and create new user window.fcWidget.user.getUUID().then((resp) => { let uuid = resp && resp.data && resp.data.uuid; if (uuid) { authenticateCB(uuid); } }); } } window.fcWidget.on("frame:statechange", function(data) { if (data.success === false && data.data.frameState === "not_authenticated") { authenticateUser(data); } }); window.fcWidget.on("user:statechange", function(data) { if (data.success) { let userData = data.data; // authenticate user success if (userData) { if (userData.userState === "authenticated") { console.log("User Authenticated"); } if (userData.userState === "created") { console.log("User Created"); } if (userData.userState === "loaded") { console.log("User Loaded"); } if (userData.userState === "identified") { console.log("User Identified"); } if (userData.userState === "restored") { console.log("User Restored"); } } } else { let userData = data.data; if (userData) { if (userData.userState === "not_loaded" || userData.userState === "unloaded" || userData.userState === "not_created" || userData.userState === "not_authenticated") { authenticateUser(userData); } } } }); } } var userReferenceId = "123"; // Call Customer backend and get the user reference id // If user exists in Customer database if (userReferenceId) { // debugger; // Call Customer backend and get the signature for userReferenceId window.fcWidgetMessengerConfig = { jwtAuthToken: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaGNoYXRfdXVpZCI6IjQ2YjgyZmEzLWJmMDMtNDJmZi1kNWIxLThjZjBkOThiOTRiMSIsIm5hbWUiOiJ0ZXN0IiwicmVmZXJlbmNlX2lkIjoiMTIzIn0.lVuWvy5kb4O25odCKgZT0vs-fZecQWM6FbLHN8lmpMWSkuiKFhVS6lfyGndE0cm6qP0WUX-82EH-hEKjMJRHjjJQw1X0gjLppOODw1espqdvYNwqDfo3ruqBSV6MT1bISnTP95Eahilqkl0OetoocGekK8-EWBnH2D1iTbyijYCGmvCRJoHYwxd3kOFVioIsC8T6pd6GEZUaimuhf_DaUT-mPf8a7m2gUbNa90DQ6jXeckUPmDbgSGci4maMEcC7E_23omrs1IgVcCJZ8oMHOXPt4-XiPw_FD37HDd_LtbeVzHcjJfsgGQmqTLN6iKgbEvTKjHsFYPuALoV7JV1Y8g" } var script = document.createElement('script'); script.src = '//fm-staging-us-app-cdnjs.s3.amazonaws.com/crm/9634889/7618539.js'; script.setAttribute('chat', 'true'); document.body.appendChild(script); } else { var script = document.createElement('script'); script.src = '//fm-staging-us-app-cdnjs.s3.amazonaws.com/crm/9634889/7618539.js'; // Replace this placeholder string from your account. Go to Admin Settings > Chat Widget Customization > Web (Embed Code) script.setAttribute('chat', 'true'); document.body.appendChild(script); } </script> </body> </html>
Component | Description |
jwtAuthToken field | The generated JWT Token is inserted in the jwtAuthToken field (line with jwtAuthToken: "your-generated-jwt-token"). |
Widget Source URL | URL for the widget source code, your-cdn-url.com/path/to/widget.js. Replace this with your actual widget script URL. You can identify the widget source code under the Embed Code tab. |
window.fcSettings | Initializes the configuration for Freshchat widget, including user authentication. |
authenticateUser Function | Authenticates user with a UUID, using an existing UUID or generating a new one when needed. Checks if userData contains freshchat_uuid:
|
User Reference ID Check | Dynamically fetches the user reference ID. In the example above, 123 is used.
|
Agent experience
If JWT user authentication is enabled, the customer contact will be shown as authenticated in the Conversation Inbox. For users with expired authentication, a cross mark will appear in the inbox.
This ensures secure and up-to-date interactions between users and agents.
Authenticated user
Non-authenticated user