In this blog, we’ll see how to create and validate a JWT(JSON Web Token) in Deno. For this, we’ll be using djwt, the absolute minimum library to make JSON Web Tokens in deno and Oak framework

Before You Get Started

This tutorial assumes you have:

  • A basic understanding of JavaScript and Deno
  • Latest Deno version installed on your system

What is JWT?

JSON Web Token is an internet standard used to create tokens for an application. These tokens hold JSON data and are cryptographically signed.

Here is how a sample Json Web Token looks like

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im9sYXR1bmRlZ2FydWJhQGdtYWlsLmNvbSIsIm

JWT is a good way of securely sending information between parties. Because JWTs can be signed—for, you can be sure the senders are who they say they are. And, as the signature is generated using the header and the payload, you can also verify that the content hasn’t been tampered with.

JWT can contain user information in the payload and also can be used in the session to authenticate the user.

If you want to know more about JSON Web Token.

How to generate JWT token in Deno

First, let’s set up a Deno server to accept requests, for it, we are using Oak framework, it is quite simple and few lines of codes as you can see below.

// index.ts
import { Application, Router } from "https://deno.land/x/oak/mod.ts";

const router = new Router();
router
  .get("/", (context) => {
    context.response.body = "JWT Example!";
  })

const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());

await app.listen({ port: 8000 });

Once our program is ready for accepting request lets import djwt functions to generate JWT token, In below code we can use a secret key, expiry time for JWT token in 1 hour from the time program will run and we are using HS256 algorithm.

Add the below code in index.ts and update the router as shown below, you can now get a brand new token on http://localhost:8000/generate

#deno #nodejs #json web tokens #jwt

How to Create and Validate JSON Web Tokens in Deno
9.30 GEEK