Articles on: Developer

How to create JSON Web Token With Javascript?

The PDF Generator API uses JSON Web Tokens (JWT) to authenticate all API requests. These tokens offer a method to establish secure server-to-server authentication by transferring a compact JSON object with a signed payload of your account’s API Key and Secret. When authenticating to the PDF Generator API, a JWT should be generated uniquely by a server-side application and included as a Bearer Token in the header of each request.

What is JSON Web Token?


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. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA. For more information about JSON Web Tokens check jwt.io.

Creating JWT with Javascript


Here is an example code on how to create a JSON Web Token with Javascript. You can see the full example in CodePen here.

import * as jose from 'jose'

createJsonWebToken(
    'the issuer',
    'the subject',
    'the secret'
  ).then((token) => {
     console.log(token)
  });

async function createJsonWebToken(iss, sub, secret) {

  const header = {
    alg: "HS256",// Token generation algorithm
    typ: "JWT"
  };

  const payload = {
    iss: iss,
    sub: sub,
    exp: Math.round(Date.now() / 1000) + 60 // token is valid for 60 seconds
  };

  return await new jose.SignJWT(payload)
    .setProtectedHeader(header)
    .sign(new TextEncoder().encode(secret));
}

Updated on: 06/09/2023

Was this article helpful?

Share your feedback

Cancel

Thank you!