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.
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.
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.
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...