TinyMCE AI with JWT authentication (Node.js) Guide
Introduction
TinyMCE AI requires setting up JSON Web Token (JWT) authentication to maintain control over AI feature access. A JWT endpoint generates and provides authorization tokens that verify users are authorized to use AI features, preventing unauthorized access. As a standard web services authorization solution, JWT is documented extensively at https://jwt.io/. TinyMCE recommends using the libraries listed on jwt.io/libraries to create JWT tokens.
This guide provides a comprehensive walkthrough for integrating TinyMCE AI with TinyMCE, including TinyMCE AI functionality, by using a Node.js server for JWT token generation. It covers project setup, server configuration, and TinyMCE customization.
What Will Be Built
Before diving into the technical details, here is what will be achieved with this guide:
-
A working TinyMCE editor running the TinyMCE AI plugin
-
A secure authentication system using JWT tokens
-
A simple Node.js server to handle the authentication
|
This guide is designed for developers new to JWT authentication and TinyMCE integration. |
Prerequisites
Before starting, ensure you have:
-
Node.js installed on the computer (to check, run
node -vin the terminal) -
A TinyMCE API key with TinyMCE AI enabled (get one from TinyMCE’s website)
-
Basic familiarity with the command line
|
Ensure the API key is ready before starting. It will be needed for both the server and client configuration. |
Quick Start Guide
If a Node.js project is not already set up, follow the steps below to create a basic environment for integrating TinyMCE AI with JWT authentication. If a project is already configured, skip this section and proceed to the JWT Configuration Requirements section.
Generate a Public/Private Key Pair
The TinyMCE AI Server requires a public key generated from the same private key that will be used on the JSON Web Token (JWT) provider endpoint. The public key(s) stored on the TinyMCE AI Server are used to ensure that content is sent by authorized users.
There are two methods for generating and adding a public key in the JWT Keys section of the account portal:
-
Generate New Keypair at Tiny Account - JWT Keys (recommended).
-
Generate a key pair locally and Import Public Key at Tiny Account - JWT Keys.
Generate a key pair using the Tiny Account JWT Keys page
The Tiny Account - JWT Keys page provides a "Generate New Keypair" option, providing a quick and secure way of generating the required keys. This will store a copy of the public key, and provide a downloadable file for both the public and private keys. Tiny does not store the private key and the key pair cannot be retrieved later.
Generate a key pair locally and add it to the account
This method involves two steps: generating the key pair locally, then adding the public key to the account portal.
Generate a key pair locally
When generating a key pair locally, use one of the supported algorithms. TinyMCE AI does not support symmetrical encryption algorithms, such as HS256. Tiny recommends using the RS256 algorithm. The following algorithms are supported:
-
RS256
-
RS384
-
RS512
-
PS256
-
PS384
-
PS512
For details on each of these algorithms, visit: RFC 7518, JSON Web Algorithms (JWA) Section 3 - Cryptographic Algorithms for Digital Signatures and MACs.
For instructions on generating a key pair locally, see: Creating a private/public key pair for Tiny Cloud.
Add a public key in the JWT Keys section of the account portal
Once a public key has been generated locally, use the "Import Public Key" option in the JWT Keys section of the account portal at: Tiny Account - JWT Keys.
JWT Configuration Requirements
This section explains what needs to be configured for JWT authentication, whether using a managed service (such as AWS or Azure JWT services) or setting up a manual endpoint.
For complete information about JWT requirements, claims, and permissions, see JWT Authentication.
A JSON Web Token (JWT) endpoint is a service for generating and providing authorization tokens to users. These tokens can then be used to verify that submitted content was sent by an authorized user and to prevent unauthorized access.
The following diagram shows how JWTs are used:
When a user opens TinyMCE AI:
-
TinyMCE AI requests a signed JWT on behalf of the user.
-
If your JWT endpoint authorizes the user, your JWT endpoint will send a JWT to TinyMCE AI, certifying the user.
-
The JWT includes a
sub(subject) claim that identifies the user. This user identifier is used to lock down conversation history, AI-generated content, and other user-specific data to individual users, ensuring privacy and data isolation. -
When the user makes a request (such as starting a chat conversation, requesting AI actions, or submitting reviews), the JWT will be sent with the request to show that the user is authorized. This JWT is verified using the public key stored on the AI service.
-
The AI service sends a response, indicating that the request was successful (or unauthorized if necessary).
JWT endpoint requirements
A JSON Web Token (JWT) endpoint for TinyMCE AI requires:
-
The endpoint or server accepts a JSON HTTP POST request.
-
User authentication: A method of verifying the user, and that they should have access to the TinyMCE AI.
-
The JWTs are generated (signed) using the private key that pairs with the public key provided to Tiny Account - JWT Keys.
-
The endpoint or server produces a JSON response with the token. TinyMCE AI will submit the token with requests to the AI service.
Required JWT claims for TinyMCE AI
JSON Web Tokens produced by the JWT endpoint must include the following claims:
aud(required)-
Type:
StringThe
audis a case-sensitive string that must match a valid API key that has the TinyMCE AI plugin enabled. sub(required)-
Type:
StringThe
subclaim identifies the user. This should be a unique identifier for the user making the request. iat(required)-
Type:
NumberThe
iatrepresents the issue timestamp, specified as the number of seconds. For example, to set the issue time to the current timestamp, calculate the issue time as the current timestamp divided by 1000.
iat: Math.floor(Date.now() / 1000), // Issue timestamp
exp(required)-
Type:
NumberThe
exprepresents the expiration timestamp, specified as the number of seconds. For example, to set a validity period of 10 minutes, calculate the expiration time as the current timestamp plus 600 seconds.
exp: Math.floor(Date.now() / 1000) + (60 * 10) // Expiration time (10 minutes)
auth(required)-
Type:
ObjectThe
authobject contains AI-specific permissions that control which features the user can access.
The following example grants access to conversations, the recommended agent model, and system actions and reviews. See Permissions for the full list of available permissions.
auth: {
ai: {
permissions: [
"ai:conversations:read",
"ai:conversations:write",
"ai:models:agent",
"ai:actions:system:*",
"ai:reviews:system:*"
]
}
}
|
See Permissions for a complete list of available permissions and best practices for configuring user access. |
Set up JWT Endpoint
The following section shows how to create a JWT endpoint manually. If using a managed JWT service (such as AWS or Azure), configure it according to the requirements above and skip to the Configure TinyMCE section.
Server Setup (jwt.js)
In the root directory, copy and paste the server setup code into the jwt.js file.
const express = require('express'); // Sets up the web server.
const jwt = require('jsonwebtoken'); // Generates and signs JWTs.
const cors = require('cors'); // Allows cross-origin requests.
const path = require('path'); // Handles file paths.
const app = express();
app.use(cors());
// Private key (Replace this with the actual key)
const privateKey = `
-----BEGIN PRIVATE KEY-----
{Your private PKCS8 key goes here}
-----END PRIVATE KEY-----
`;
app.use(express.static(path.join(__dirname, 'public')));
// JWT token generation endpoint
app.post('/jwt', (req, res) => {
const payload = {
aud: 'no-api-key', // Replace with the actual API key
sub: 'user-id', // Replace with actual user identifier
iat: Math.floor(Date.now() / 1000), // Issue timestamp
exp: Math.floor(Date.now() / 1000) + (60 * 10), // Expiration time (10 minutes)
// Permissions control which AI features the user can access. See the Permissions page for full details.
auth: {
ai: {
permissions: [
'ai:conversations:read',
'ai:conversations:write',
'ai:models:agent',
'ai:actions:system:*',
'ai:reviews:system:*'
]
}
}
};
try {
// Tokens are signed with the RS256 algorithm using the private key
const token = jwt.sign(payload, privateKey, { algorithm: 'RS256' });
res.json({ token });
} catch (error) {
res.status(500).send('Failed to generate JWT token.');
console.error(error.message);
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
|
The JWT payload includes an |
Configure TinyMCE
Web Page (public/index.html)
Inside the public folder where the index.html file was created, add the HTML setup code.
<!DOCTYPE html>
<html>
<head>
<title>{productname} with {pluginname}</title>
<script
src="https://cdn.tiny.cloud/1/no-api-key/tinymce/8/tinymce.min.js"
referrerpolicy="origin"
crossorigin="anonymous">
</script>
<script>
tinymce.init({
selector: 'textarea',
plugins: 'tinymceai',
toolbar: 'tinymceai-chat tinymceai-quickactions tinymceai-review',
// tinymceai_token_provider fetches a token from the `/jwt` endpoint.
// This demo does not verify user session; it simulates an already-authenticated user. Integrate with your auth before returning tokens.
tinymceai_token_provider: () => {
return fetch('http://localhost:3000/jwt', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}).then(response => response.json());
},
});
</script>
</head>
<body>
<h1>{pluginname} Demo</h1>
<textarea>
Welcome to {productname}! Try the AI features like chat, quick actions, and review.
</textarea>
</body>
</html>
Model configuration
Model selection can be configured using tinymceai_default_model and tinymceai_allow_model_selection. See Chat model configuration for details. Model access is controlled by JWT permissions; see Model permissions for available model permissions and AI Models for the list of available models.
tinymce.init({
selector: 'textarea',
plugins: 'tinymceai',
toolbar: 'tinymceai-chat tinymceai-quickactions tinymceai-review',
tinymceai_default_model: 'agent-1',
tinymceai_allow_model_selection: true,
// This demo does not verify user session; it simulates an already-authenticated user. Integrate with your auth before returning tokens.
tinymceai_token_provider: () => {
return fetch('http://localhost:3000/jwt', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}).then(response => response.json());
},
});
Configuration Steps
Add API Key
-
Replace
no-api-keyin both files with the actual TinyMCE API key -
The API key should be the same in both the HTML script source and the JWT payload
Add Private Key
-
Replace the private key placeholder in
jwt.jswith the actual private key -
Make sure it’s in
PKCS8format -
Keep this key secure and never share it publicly
Configure AI Permissions
-
Adjust the
auth.ai.permissionsarray in the JWT payload based on requirements -
See Permissions for available permissions and best practices
Configure model selection (optional)
-
Add
tinymceai_default_modelandtinymceai_allow_model_selectionto the editor config if needed -
See Model configuration for details
Running the Project
-
Start the server:
node jwt.js -
Open the browser to:
http://localhost:3000 -
The following should be visible:
-
The TinyMCE editor
-
AI feature buttons in the toolbar (tinymceai-chat, tinymceai-quickactions, tinymceai-review)
-