Authenticating with JWT in Deno

Can someone guide me on generating and authenticating JSON Web Token in Deno?

Being a newbie to the Deno environment, I would greatly appreciate a code snippet to kickstart my journey with JWT in Deno.

Answer №1

In this example, we demonstrate the process of generating a JWT with an HS256 signature, verifying it, and extracting the payload.

jwtdemo.ts (built on Version 2.4 of djwt):

import { create, verify , getNumericDate, Payload, Header} from "https://deno.land/x/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8886198dad">[email protected]</a>/mod.ts";

const encoder = new TextEncoder()
var keyBuf = encoder.encode("mySuperSecret");

var key = await crypto.subtle.importKey(
  "raw",
  keyBuf,
  {name: "HMAC", hash: "SHA-256"},
  true,
  ["sign", "verify"],
)

const payload: Payload = {
  iss: "deno-demo",
  exp: getNumericDate(300), // expires in 5 min.
};

const algorithm = "HS256"

const header: Header = {
  alg: algorithm,
  typ: "JWT",
  foo: "bar"  // custom header
};

const jwt = await create(header, payload, key)

console.log(jwt);

// create a different key to test the verifcation
/*keyBuf = encoder.encode("TheWrongSecret");
key = await crypto.subtle.importKey(
  "raw",
  keyBuf,
  {name: "HMAC", hash: "SHA-256"},
  true,
  ["sign", "verify"],
)
*/

try {
  const payload = await verify(jwt, key); 
    console.log("JWT is valid");
    console.log(payload);
}
catch(_e){
  const e:Error= _e;
  console.log(e.message);
}

The latest version of djwt leverages the Web Crypto API which has been supported since Deno 1.11. The functions create and verify now require the key parameter as a CryptoKey object, mandating the creation of a proper key object instead of a simple string.

The utility method getNumericDate(exp) automatically configures a correct Unix timestamp by adding the specified number of seconds to the current time or using the provided date input directly.

You can execute the demonstration above, and all imported modules will be fetched automatically:

deno run jwtdemo.ts

The output would be:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImZvbyI6ImJhciJ9.eyJpc3MiOiJkZW5vLWRlbW8iLCJleHAiOjE2MzMzNzUyODl9.FBYgDrpG9RXJSfgme-430UyFLvdNTNliYTKGiWajksQ
JWT is valid
{ iss: "deno-demo", exp: 1633375289 }

If you use an incorrect signature (uncomment the code snippet with the wrong secret for testing):

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImZvbyI6ImJhciJ9.eyJpc3MiOiJkZW5vLWRlbW8iLCJleHAiOjE2MzMzNzU0MDd9.F3szgyrTJSQG3m1a82OJkKqKIDD32Q21ZchAVAj74bk
The jwt's signature does not match the verification signature.

An interesting distinction in Deno compared to node.js is the utilization of predefined interfaces like Header and Payload instead of plain JSON, ensuring data integrity.

Trying to set

const algorithm = "XS256"   // instead of "HS256"

would trigger a failure due to algorithm mismatch:

error: Type '"XS256"' is not assignable to type 'Algorithm'.
...
Argument of type '"XS256"' is not assignable to parameter of type 'AlgorithmInput'.
...

This sample code showcases the capabilities of djwt version 2.4, supporting various signature algorithms like HSxxx, RSxxx, PSxxx, and ESxxx. Future additions may include more algorithms compatible with Deno's cryptographic modules.

Refer to this answer for details on verifying an RS256-signed token in Deno.

Note: This revision covers the changes in the djwt library API introduced in version 2.4. The original post was based on djwt v1.9. View the previous version here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ng-model used within an *ngFor loop is not displaying the correct value

I am working with a JSON file in my Angular2 App. The specific JSON object I am referring to is named tempPromotion and I am trying to access the data within ['results'] like this: tempPromotion['response_payload']['ruleset_list ...

The correlation between the node.js version and the @types/node version

I recently started exploring node.js and decided to experiment with using TypeScript alongside it. After running npm install @types/node, I found that the latest version available was 7.0.4: $ npm install @types/node <a href="/cdn-cgi/l/email-protectio ...

Adonisjs latest version (v5) model creation command malfunctioning

Using Adonisjs v5 The controller command works fine with: node ace make:controller Posts However, the new model creation command is not working: node ace:make model Post When running the make model command, an error occurs: An error message stating &ap ...

React with TypeScript presents an unusual "Unexpected token parsing error"

Recently, I encountered an issue with my helper function that was originally written in JavaScript and was functioning perfectly. However, as soon as I introduced TypeScript into the mix, strange behaviors started to surface. Here is the snippet of code fr ...

What in the world is going on with this Typescript Mapped type without a right-hand side?

I encountered a situation where my React component had numerous methods for toggling boolean state properties. Since these functions all did the same thing, I wanted to streamline the process by creating a common function for toggling properties. Each met ...

Tips for integrating TypeScript with Vue.js and Single File Components

After extensive searching online, I have struggled to find a straightforward and up-to-date example of setting up Vue.js with TypeScript. The typical tutorials out there either are outdated or rely on specific configurations that don't apply universal ...

Issue with Angular 18 component not being displayed or identified

Recently, I began building an Angular 18 application and encountered an issue with adding my first component as a standalone. It appears that the app is not recognizing my component properly, as it does not display when added as an HTML tag in my app.compo ...

Creating a nested observable in Angular2: A step-by-step guide

Currently, I am exploring a new approach in my Angular2 service that involves using observables. The data source for this service will initially be local storage and later updated when an HTTP call to a database returns. To achieve this dynamic updating of ...

Select characteristics with designated attribute types

Is there a way to create a type that selects only properties from an object whose values match a specific type? For example: type PickOfValue<T, V extends T[keyof T]> = { [P in keyof (key-picking magic?)]: T[P]; }; I am looking for a solution w ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...

"Encountering Issues with Angular's Modules and EntryComponents during Lazy Loading

Upon lazy loading an Angular module, I encountered an issue when trying to open my DatesModal that resulted in the following error: No component factory found for DatesModal. Have you included it in @NgModule.entryComponents? The declaration and entryCom ...

Executing methods sequentially in the ngOnInit lifecycle hook consecutively

Working with Angular15 has presented me with a challenge. In my app.component.ts file, I have two methods: “ngOnInit()”, as shown below. public ngOnInit(): void { this.getToken(); this.UserLoggedIn(); } I am looking to run the above two functions in ...

Transform two sets of string arrays into nested objects

I have a challenge where I need to take two arrays (which are arrays of integers) and create nested objects using the "Cartesian Product" in both directions. I am considering whether this is more of a permutation problem and suspect that it may involve u ...

forEach was unable to determine the appropriate data types

define function a(param: number): number; define function b(param: string): string; define function c(param: boolean): boolean; type GeneralHooks<H extends (...args: any[]) => any> = [H, Parameters<H>] const obj = { a: [a, [1]] as Gene ...

What is the best way to destructure a blend of React props and my own custom props in my code?

I have a requirement to develop a custom React component that serves as a wrapper for the Route component in order to create secure routes. The challenge I am facing is how to access the element property, which is typically specified in the <Route> e ...

Angular is throwing an error stating that the argument type 'typeof MsalService' cannot be assigned to the parameter type 'MsalService'

I'm currently facing a challenge in creating an instance of a class in TypeScript/Angular. Within my project, there is a specific scenario where I need to call a method from an exported function that is located within another class in TypeScript. co ...

How to Create a Flexible Angular Array Input Component

I have been working on developing reusable form input components using Angular's reactive forms. However, I am currently encountering challenges with my FormArray input component. To overcome some issues, I had to resort to using double-type casting ...

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

React refs should always be validated for null or never values to avoid any potential issues

As I set up a react ref to be used in useEffect, the compiler is throwing an error stating that myRef.current evaluates to never: import React, {useRef, useState} from 'react' export default function RefProblem() { const myRef = useRef(null ...

Reorganizing Firebase data in Ionic 2

I am currently working on an exciting project to develop an Ionic notes application, where users can easily rearrange items in the list using the reorderArray() function. However, I encountered an issue with Firebase resulting in an error message related t ...