Export to PDF with JWT authentication (Node.js) Guide

Introduction

Export to PDF requires setting up JSON Web Token (JWT) authentication to maintain control over file security. A JWT endpoint generates and provides authorization tokens that verify submitted content is sent by authorized users, preventing unauthorized access. As a standard web services authorization solution, JWT is documented extensively at https://jwt.io/.

This guide provides a comprehensive walkthrough for integrating Export to PDF with TinyMCE, including Export to PDF functionality, by using a Node.js server for JWT token generation. It covers project setup, server configuration, and TinyMCE customization.

What You’ll Build

Before diving into the technical details, here’s what you’ll achieve with this guide:

  • A working TinyMCE editor running Export to PDF plugin.

  • A secure authentication system using JWT token.

  • 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 your computer

  • A TinyMCE API key (get one from TinyMCE’s website)

  • Basic familiarity with the command line

Make sure you have your API key ready before starting. You’ll need it for both the server and client configuration.

Quick Start Guide

Project Setup

# Create and enter project directory
mkdir tinymce-my-app
cd tinymce-my-app

# Initialize project
npm init -y

# Install required packages
npm install express cors jsonwebtoken

Verify that the package.json file now includes the required dependencies.

Create Project Structure

# Create the public folder for your web files
mkdir public
touch public/index.html
touch jwt.js

Your project should look like this:

/tinymce-my-app
  /public
    index.html  (TinyMCE webpage)
  jwt.js        (Server code)
  package.json  (Project configuration)
  1. Inside the public folder where you created the index.html file add the HTML setup code (refer to the Web Page (public/index.html) section).

Setup

Setting up JWT authentication

To set up JSON Web Token (JWT) authentication for TinyMCE Export to PDF:

  1. Add a public key to your Tiny Account, login.

  2. Set up a JSON Web Token (JWT) Provider endpoint via Tiny Account - JWT Keys

  3. Configure your TinyMCE to use the JWT endpoint.

The Export to PDF Server requires a public key generated from the same private key that will be used on your JSON Web Token (JWT) provider endpoint. The public key(s) stored on the Export to PDF Server are used to ensure that content is sent by authorized users.

There are two methods for generating and adding a public key to your API key:

  1. The secure key pair generator at Tiny Account - JWT Keys (recommended).

  2. Generate a key pair locally and add the public key to Tiny Account - JWT Keys.

Generate a key pair using the Tiny Account JWT Keys page

The Tiny Account - JWT Keys page provides a private/public key generator, providing a quick and secure way of generating the required keys. This generator 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

When generating a key pair locally, use one of the supported algorithms. Export to PDF 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 instructions on generating a key pair locally, see: Creating a private/public key pair for Tiny Cloud.

Add a public key to the Tiny Cloud API key

Once a public key has been generated, add the public key to the Tiny Cloud API key at: Tiny Account - JWT Keys.

Set up a JSON Web Token (JWT) endpoint

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:

JSON Web Token Call Flow
Figure 1. JSON Web Token Call Flow

When a user opens Export to PDF:

JWT endpoint requirements

A JSON Web Token (JWT) endpoint for Export to PDF 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 Export to PDF.

  • 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. Export to PDF will submit the token with requests to the Export to PDF Server.

Required JWT claims for Export to PDF

JSON Web Tokens produced by the JWT endpoint must include the following claims:

aud (required)

Type: String

The aud is case-sensitive string that must match a valid API key that has the Export to PDF plugin enabled.

iat (required)

Type: Number

The iat represents 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.

Example
iat: Math.floor(Date.now() / 1000), // Issue timestamp
exp (required)

Type: Number

The exp represents 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.

Example
exp: Math.floor(Date.now() / 1000) + (60 * 10) // Expiration time (10 minutes)
  1. In the root directory, copy and paste the server setup code into the jwt.js file (refer to the Configuring the Node.js Server for JWT Token Generation section).

Server Setup (jwt.js)

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());

// Your private key (Replace this with your 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: 'YOUR-API-KEY', // Replace with your actual API key
        iat: Math.floor(Date.now() / 1000), // Issue timestamp
        exp: Math.floor(Date.now() / 1000) + (60 * 10) // Expiration time (10 minutes)
    };

    try {
        // Tokens are signed with the RS256 algorithm using your 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}`);
});

Web Page (public/index.html)

<!DOCTYPE html>
<html>
<head>
  <title>TinyMCE with PDF Export</title>
  <script
    src="https://cdn.tiny.cloud/1/YOUR-API-KEY/tinymce/7/tinymce.min.js"
    referrerpolicy="origin">
  </script>
  <script>
    tinymce.init({
      selector: 'textarea',
      plugins: 'exportpdf',
      toolbar: 'exportpdf',
      exportpdf_converter_options: {
        'format': 'Letter',
        'margin_top': '1in',
        'margin_right': '1in',
        'margin_bottom': '1in',
        'margin_left': '1in'
      },

      // exportpdf_token_provider fetches a token from the `/jwt` endpoint.
      exportpdf_token_provider: () => {
        return fetch('http://localhost:3000/jwt', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
        }).then(response => response.json());
      },
    });
  </script>
</head>
<body>
  <h1>TinyMCE Export to PDF Demo</h1>
  <textarea>
    Welcome to TinyMCE! Try the Export to PDF feature.
  </textarea>
</body>
</html>

Configuration Steps

Add Your API Key

  • Replace YOUR-API-KEY in both files with your actual TinyMCE API key

  • The API key should be the same in both the HTML script source and the JWT payload

Add Your Private Key

  • Replace the private key placeholder in jwt.js with your actual private key

  • Make sure it’s in PKCS8 format

  • Keep this key secure and never share it publicly

Running Your Project

  1. Start the server:

    node jwt.js
  2. Open your browser to: http://localhost:3000

  3. You should see:

    • The TinyMCE editor

    • An "Export to PDF" button in the toolbar