"JS Kyle: Utilizing JWT for Signing and Encrypting Data

I am currently using jose for signing and encrypting JWTs, but I am facing an issue when trying to sign and then encrypt the entire JWT.

When it comes to signing my JWT, I utilize the following function:

const secretKey = process.env.JWT_SECRET;
const key = new TextEncoder().encode(secretKey);

export async function _encrypt(payload: any) {
  return await new SignJWT(payload)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("10 sec from now")
    .sign(key);
}

For encryption, I use the following code snippet (which works when passing a JWT object):

const now = () => (Date.now() / 1000) | 0;

const alg = "dir";
const enc = "A256CBC-HS512";

...

sync function encrypt({
  payload,
  maxAge,
}: {
  payload: JWTPayload;
  maxAge: number;
}): Promise<string> {
  const secret: Uint8Array = randomBytes(32);
  const salt = randomBytes(16);
  const encryptionSecret: Uint8Array = await hkdf(
    "sha256",
    secret,
    salt,
    "Generated Encryption Key",
    32
  );
  
  return new EncryptJWT(payload)
    .setProtectedHeader({ alg, enc })
    .setIssuedAt()
    .setExpirationTime(now() + maxAge)
    .setJti(crypto.randomUUID())
    .encrypt(encryptionSecret);
}

The problem arises because EncryptJWT only accepts a JWT object, as indicated by the error message in the console:

error TypeError: JWT Claims Set MUST be an object

Answer №1

If you need to sign and encrypt your data, you can do so by utilizing the SignJWT class for signing and then the CompactEncrypt method for encrypting the signed data. For a detailed example, check out https://github.com/panva/jose/issues/112, making sure to replace the key management with your own secrets and selecting the appropriate algorithms.

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 jQuery .load function does not function properly when an ajax query is already underway

My web application utilizes dynamic loading of content within the same div (.content) through either an ajax request or a .load() request. An example of the ajax request code snippet is: $(document).on('click', '.button1', functio ...

Utilizing Vue.js to add functionality for navigation buttons allowing users to move between survey questions

In my Vue.js component, I've written code to show survey questions in a mobile app for users. Here is a snippet of the code: <div class="col-12 p-0" v-for="( i, index ) in questions" :key="i"> <p cl ...

"Revolutionary AJAX-enabled PHP social commenting system with multi-form support

Why is it that when I submit forms using these ajax functions in PHP, they only send to the first form on the page? I have multiple forms under each article and I want them to be submitted separately. What am I doing wrong? ...

Ensuring that EJS IF/ELSE statements are evaluated accurately

I am encountering an issue where my variable 'answer' is returning the string 'success' and displaying correctly in the view. However, the IF/ELSE statement always seems to evaluate to the ELSE condition and displays 'no' inst ...

Tips for transferring a function from a Node.js server to a client

Hey everyone, I'm trying to achieve the following: On the Node server side: var fn = function(){ alert("hello"); } I am looking for a way to send this function to the client side. I am currently using AngularJS, but I am open to other solution ...

Error in JSON parsing: Unexpected token 'u' at the beginning of the input in Angular2

I attempted to create a server using dummy data. Below is the System.js Config I have implemented (given that my routing is slightly different, this setup has been working well so far) System.config({ // baseURL to node_modules b ...

Guide for creating a CORS proxy server that can handle HTTPS requests with HTTP basic authentication

For my http requests, I've been utilizing a CORS-Proxy which works well for me. However, I recently stumbled upon an API for sending emails which requires http basic authentication for https requests. I'm uncertain of how to go about implementing ...

Can Next.js 13 layout be cancelled in any way?

My website has three main pages: /, /accounts, and /signin I'm looking to implement a dashboard layout for the first two pages, while keeping a normal layout for the signin page. However, I'm stuck on how to achieve this. If I add the dashboard ...

Error: Child component received an undefined prop

Within my parent component, I have three child components. The first child component is a form that, upon submission, passes data to the second and third child components through props via the parent component. However, in one of the child components, the ...

Angular updates location, but browser redirects to incorrect page

I want my application to redirect non-logged in users to a login page. Following advice from a popular source, the app listens for routeChangeStart events like this: $rootScope.$on("$routeChangeStart", function(event, next, current) { if ($rootScope.c ...

Display HTML content in autocomplete using jQuery UI

I implemented a search feature on my website using jQueryUI, similar to how it works on Facebook. Below is the jQuery code: //search main function split( val ) { return val.split( ); } function extractLast( term ) { return split( term ).pop(); } ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

You must add the module-alias/register to each file in order to use path aliases in

I am currently utilizing typescript v3.6.4 and have the following snippet in my tsconfig.json: "compilerOptions": { "moduleResolution": "node", "baseUrl": "./src", "paths": { "@config/*": ["config/*"], "@config": ["config"], ...

Steps for generating a div, link, and image that links to another image using Javascript

Hey there, I have a cool picture to share with you! <img src="cards.png" id="img"> <!--CARD PICTURE--> Check out what I want to do with it: <div class="container_img"> <img src="cards.png" id="img"> <!--CARD PICTURE--> ...

Find the differences between the values in two arrays of objects and eliminate them from the first array

const arrayOne = [ { id: 22, value: 'hello' }, { id: 33, value: 'there' }, { id: 44, value: 'apple' } ]; const arrayTwo = [ { id: 55, value: 'world' }, { id: 66, value: 'banana' }, ...

Leverage the power of NextJS to create a seamlessly persistent layout featuring the

Currently, I am in the process of transitioning a project from React to NextJS. The project's layout includes a common component which is a Leaflet Map. In Next JS, I utilize "next/dynamic" to load the map. Previously, React used react-router-dom@v6. ...

Oops! Vue.js is throwing a compile error involving unused variables and undefined variables

I'm currently working on developing a new Vue.js component, but I'm encountering an error when launching the application. The specific error message is displayed below: https://i.sstatic.net/0MQxl.png <template> <div class="hello" ...

Trouble with Vue 3 watch not persisting after page refresh

Attempting to create a Vue application that supports two languages, utilizing local storage and store to store the selected language. Initially, everything appears to be functioning correctly. After the user logs in, the default language is displayed in b ...

Safeguard sub-pages with Passport Local if the user has not logged in

I attempted to follow a tutorial on local authentication with Passport and Express, but I am encountering difficulties in protecting my pages for users who are not logged in. My goal is to redirect them to the login page. I experimented with creating midd ...

What could be the reason for the <div> style on the webpage not changing?

I'm currently working on a Django project where I've encountered a challenge. I have div containers with dynamic IDs, where the ID is fetched from the database and automatically injected into the HTML. Here's an example of how the dynamic I ...