Creating and signing a JWT
JWTs are used to authenticate users from the Featurebase Messenger, widgets and the web portal through SSO.
Written By Bruno H
Last updated 4 days ago
Creating a JWT
To create and sign a JWT:
Start by getting your private key from Settings → Access & Security → Security. Store it on your server and make sure not to share it with anyone!
On your server, generate a JWT with your customer data using the example below.
Install required packages
npm install --save jsonwebtokenpip install pyjwt// Instructions here
https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/// Instructions here
https://github.com/jwtk/jjwt#installgo get github.com/golang-jwt/jwtcomposer require firebase/php-jwtGenerate the JWT
const jwt = require("jsonwebtoken");
// IMPORTANT: NEVER EXPOSE ON CLIENT SIDE!!
const JWT_SECRET = "JWT_SECRET_VALUE";
function generateJWTToken(user) {
const userData = {
name: user.name,
// Both email and userId should be provided when possible
// At minimum, either email or userId must be present
email: user.email,
userId: user.id,
profilePicture: "https://example.com/images/yourcustomer.png",
// Add any optional custom attributes - must be configured from settings to work
title: "Product Manager",
plan: "Premium",
number: "123",
// Tags
// tags: ["Tag name1"] // Optional - tag user with configured tag names
// locale: "en", // optional, provide expected language for user
// Optional fields
companies: [
{
id: "987654321", // required
name: "Business Inc. 23", // required
monthlySpend: 500, // optional
createdAt: "2023-05-19T15:35:49.915Z", // optional
// Add any optional custom attributes - must be configured from settings to work
industry: "Fintech",
location: "Canada",
},
],
};
return jwt.sign(userData, JWT_SECRET, {
algorithm: "HS256",
});
}import jwt
# IMPORTANT: NEVER EXPOSE ON CLIENT SIDE!!
JWT_SECRET = "JWT_SECRET_VALUE"
def generateJWTToken(user):
user_data = {
'name': user['name'],
# Both email and userId should be provided when possible
# At minimum, either email or userId must be present
'email': user['email'],
'userId': user['id'],
'profilePicture': "https://example.com/images/yourcustomer.png",
# Add any optional custom attributes - must be configured from settings to work
'title': "Product Manager",
'plan': "Premium",
'number': "123",
# Tags
# 'tags': ['Tag name1'] # Optional - tag user with configured tag names
# locale: "en", # optional, provide expected language for user
# Optional fields
'companies': [
{
'id': "987654321", # required
'name': "Business Inc. 23", # required
'monthlySpend': 500, # optional
'createdAt': "2023-05-19T15:35:49.915Z", # optional
# Add any optional custom attributes - must be configured from settings to work
'industry': "Fintech",
'location': "Canada",
},
],
}
return jwt.encode(user_data, JWT_SECRET, algorithm='HS256')using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
// IMPORTANT: NEVER EXPOSE ON CLIENT SIDE!!
const string JWT_SECRET = "JWT_SECRET_VALUE";
public string generateJWTToken(User user)
{
var userData = new List<Claim>
{
new Claim("name", user.Name),
// Both email and userId should be provided when possible
// At minimum, either email or userId must be present
new Claim("email", user.Email),
new Claim("userId", user.Id),
new Claim("profilePicture", "https://example.com/images/yourcustomer.png"),
// Add any optional custom attributes - must be configured from settings to work
new Claim("title", "Product Manager"),
new Claim("plan", "Premium"),
new Claim("number", "123"),
// locale: "en", // optional, provide expected language for user
// Optional fields
new Claim("companies", JsonConvert.SerializeObject(new[]
{
new
{
id = "987654321", // required
name = "Business Inc. 23", // required
monthlySpend = 500, // optional
createdAt = "2023-05-19T15:35:49.915Z", // optional
// Add any optional custom attributes - must be configured from settings to work
industry = "Fintech",
location = "Canada",
}
})),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JWT_SECRET));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
claims: userData,
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.*;
// IMPORTANT: NEVER EXPOSE ON CLIENT SIDE!!
private static final String JWT_SECRET = "JWT_SECRET_VALUE";
public String generateJWTToken(User user) {
Map<String, Object> userData = new HashMap<>();
userData.put("name", user.getName());
// Both email and userId should be provided when possible
// At minimum, either email or userId must be present
userData.put("email", user.getEmail());
userData.put("userId", user.getId());
userData.put("profilePicture", "https://example.com/images/yourcustomer.png");
// Add any optional custom attributes - must be configured from settings to work
userData.put("title", "Product Manager");
userData.put("plan", "Premium");
userData.put("number", "123");
// locale: "en", // optional, provide expected language for user
// Optional fields
List<Map<String, Object>> companies = new ArrayList<>();
Map<String, Object> company = new HashMap<>();
company.put("id", "987654321"); // required
company.put("name", "Business Inc. 23"); // required
company.put("monthlySpend", 500); // optional
company.put("createdAt", "2023-05-19T15:35:49.915Z"); // optional
// Add any optional custom attributes - must be configured from settings to work
company.put("industry", "Fintech");
company.put("location", "Canada");
companies.add(company);
userData.put("companies", companies);
return Jwts.builder()
.setClaims(userData)
.signWith(SignatureAlgorithm.HS256, JWT_SECRET)
.compact();
}import (
"github.com/golang-jwt/jwt"
)
// IMPORTANT: NEVER EXPOSE ON CLIENT SIDE!!
var JWT_SECRET = []byte("JWT_SECRET_VALUE")
func generateJWTToken(user User) (string, error) {
userData := jwt.MapClaims{
"name": user.Name,
// Both email and userId should be provided when possible
// At minimum, either email or userId must be present
"email": user.Email,
"userId": user.Id,
"profilePicture": "https://example.com/images/yourcustomer.png",
// Add any optional custom attributes - must be configured from settings to work
"title": "Product Manager",
"plan": "Premium",
"number": "123",
// locale: "en", // optional, provide expected language for user
// Optional fields
"companies": []map[string]interface{}{
{
"id": "987654321", // required
"name": "Business Inc. 23", // required
"monthlySpend": 500, // optional
"createdAt": "2023-05-19T15:35:49.915Z", // optional
// Add any optional custom attributes - must be configured from settings to work
"industry": "Fintech",
"location": "Canada",
},
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, userData)
return token.SignedString(JWT_SECRET)
}use Firebase\JWT\JWT;
// IMPORTANT: NEVER EXPOSE ON CLIENT SIDE!!
$JWT_SECRET = "JWT_SECRET_VALUE";
function generateJWTToken($user) {
$userData = array(
"name" => $user['name'],
// Both email and userId should be provided when possible
// At minimum, either email or userId must be present
"email" => $user['email'],
"userId" => $user['id'],
"profilePicture" => "https://example.com/images/yourcustomer.png",
// Add any optional custom attributes - must be configured from settings to work
"title" => "Product Manager",
"plan" => "Premium",
"number" => "123",
// locale: "en", // optional, provide expected language for user
// Optional fields
"companies" => array(
array(
"id" => "987654321", // required
"name" => "Business Inc. 23", // required
"monthlySpend" => 500, // optional
"createdAt" => "2023-05-19T15:35:49.915Z", // optional
// Add any optional custom attributes - must be configured from settings to work
"industry" => "Fintech",
"location" => "Canada",
),
),
);
return JWT::encode($userData, $JWT_SECRET, 'HS256');
}Make sure you replace JWT_SECRET with the secret for your organization.
Testing if your generated JWT works
Now go to Settings → Access & Security → Security and validate your JWT. This will tell you if you’ve done everything correctly.
Important: Set up custom attributes
If you are adding custom attributes in the data, you must configure them first. Otherwise, they are not gonna show up and persist.
Please make sure to configure them by following this guide →
Next steps
That’s it! Now you can use the freshly generated JWT to authenticate users in Featurebase.
Please continue from the original guide that linked to this article to finish your installation.
More in Identity & security
Identifying users & syncing dataWeb portal single sign-on (SSO) setupStill need help? Ask the team