JWT Token Generation

Complete guide to generating JSON Web Tokens for AI Smart Text Editor authentication

Back to Documentation

JWT Token Generation Guide

This guide provides detailed instructions for generating JSON Web Tokens (JWTs) for authenticating with the AI Smart Text Editor. JWTs are used to securely transmit user and tenant information between your application and LeapHubAI services.

What is a JWT?

A JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

A JWT consists of three parts separated by dots (.):

  1. Header: Metadata about the token, including the signing algorithm.
  2. Payload: The claims or information being transmitted.
  3. Signature: Used to verify the token's authenticity and integrity.

The structure of a JWT is:

Base64UrlEncode(Header).Base64UrlEncode(Payload).Base64UrlEncode(Signature)

JWT Structure for AI Smart Text Editor

1. Header

The header typically consists of two parts:

  • alg (Algorithm): The signing algorithm being used (e.g., HS256). This must match the algorithm for which LeapHubAI provides you a secret/key.
  • typ (Type): The type of the token, which is always JWT.

Header Example (JSON object, before Base64Url encoding):

{
  "alg": "HS256",
  "typ": "JWT"
}

2. Payload

The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data.

For integration with the AI Smart Text Editor, the payload must include the following claims:

  • sub (Subject): This must be the unique ID of your user.
  • tenant: This must be the unique ID of the account or organization the user belongs to in your system.

It is also highly recommended to include the following standard registered claims for security:

  • iat (Issued At): The time at which the JWT was issued (Unix timestamp).
  • exp (Expiration Time): The time after which the JWT must not be accepted (Unix timestamp).
  • jti (JWT ID): A unique identifier for the token, can help prevent reuse.

Payload Example (JSON object, before Base64Url encoding):

{
  "sub": "user_id_from_your_system",
  "tenant": "account_id_from_your_system",
  "iat": 1678886400,
  "exp": 1678890000,
  "jti": "unique_token_identifier_string"
}

Note: Unix timestamps are in seconds since the epoch.

3. Signature

To create the signature, you need:

  1. The Base64Url encoded Header.
  2. The Base64Url encoded Payload.
  3. A secret key (if using a symmetric algorithm like HS256) or a private key (if using an asymmetric algorithm like RS256). This key is provided by LeapHubAI and must be kept confidential.

The signing input is formed by concatenating the encoded header and encoded payload with a period (.) in between:

signing_input = Base64UrlEncode(Header) + "." + Base64UrlEncode(Payload)

The signature is then calculated using the specified algorithm (alg from the header) and the secret/private key:

raw_signature = Algorithm(signing_input, key)

For example, with HS256:

raw_signature = HMACSHA256(signing_input, your-LeapHubAI-secret-key)

The your-LeapHubAI-secret-key will be provided by LeapHubAI or available in your workspace settings.

The final JWT is constructed by concatenating the Base64Url encoded Header, Base64Url encoded Payload, and the Base64Url encoded raw Signature, each separated by a dot:

jwt_string = Base64UrlEncode(Header) + "." + Base64UrlEncode(Payload) + "." + Base64UrlEncode(raw_signature)

Implementation with Libraries

It is highly recommended to use established JWT libraries in your backend programming language rather than implementing JWT generation manually. These libraries handle the complex encoding and cryptographic operations correctly and securely.

Node.js/JavaScript

Install the jsonwebtoken library:

npm install jsonwebtoken

Example implementation:

const jwt = require('jsonwebtoken');

function generateJWT(userId, tenantId, secretKey) {
const payload = {
sub: userId,
tenant: tenantId,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (60 \* 60)
};

return jwt.sign(payload, secretKey, { algorithm: 'HS256' });
}

Python

Install the PyJWT library:

pip install PyJWT

Example implementation:

import jwt
import time
import uuid

def generate_jwt(user_id, tenant_id, secret_key):
payload = {
'sub': user_id,
'tenant': tenant_id,
'iat': int(time.time()),
'exp': int(time.time()) + 3600
}

return jwt.encode(payload, secret_key, algorithm='HS256')

PHP

Install the firebase/php-jwt library:

composer require firebase/php-jwt

Example implementation:

<?php
    require_once 'vendor/autoload.php';
    use Firebase\JWT\JWT;
    use Firebase\JWT\Key;

    function generateJWT($userId, $tenantId, $secretKey) {
    $payload = [
        'sub' => $userId,
        'tenant' => $tenantId,
        'iat' => time(),
        'exp' => time() + 3600
    ];

    return JWT::encode($payload, $secretKey, 'HS256');

}

C# (.NET)

Install the System.IdentityModel.Tokens.Jwt package:

dotnet add package System.IdentityModel.Tokens.Jwt

Example implementation:

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;

public string GenerateJWT(string userId, string tenantId, string secretKey)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(secretKey);

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[]
        {
            new Claim("sub", userId),
            new Claim("tenant", tenantId)
        }),
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);

}

Security Best Practices

  • Keep your secret key confidential: Never expose your LeapHubAI secret key in client-side code or public repositories.
  • Use appropriate expiration times: Set reasonable expiration times for your tokens (typically 1-24 hours).
  • Validate on the server: Always generate JWTs on your secure backend server, never in client-side code.
  • Use HTTPS: Always transmit JWTs over secure connections.

Troubleshooting

Common Issues

  • Invalid signature: Ensure you're using the correct secret key provided by LeapHubAI.
  • Token expired: Check that your system time is correct and tokens haven't exceeded their expiration time.
  • Missing required claims: Verify that both sub and tenant claims are included in your payload.
  • Algorithm mismatch: Ensure the algorithm in your header matches what LeapHubAI expects (typically HS256).

For additional support, please refer to our troubleshooting guide or contact our support team.