Jose authentication is encountering issues with verifying JWT

My Next.js/Clerk.js middleware setup looks like this:

import { authMiddleware } from "@clerk/nextjs";
import { jwtVerify } from "jose";

export default authMiddleware({
  publicRoutes: ["/", "/contact", "/pricing", "/api/webhooks/user", "/api/reviews/add", "/api/user"],
  afterAuth (auth, req, evt) {
    const secret = new TextEncoder().encode (process.env.CLERK_PUBLIC_KEY)
    const decoded = jwtVerify ("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkZXYiOiJkdmJfMlpFZkVyUG91dHBuaFptQXZzdk0zMkVadkVhIiwiaWQiOiJjbGllbnRfMlpFZkpieUFQUXRWbVB4Q3R2SER4SE04a2tCIiwicm90YXRpbmdfdG9rZW4iOiJmaWNid25rZDE0aTVpNm5rZzJicjc1ODl5NWZqeGloemloZDk2dnprIn0.qURs213vHtEe_2DTmOVN8jCPCJhQfIIEjWLMIXgIVYs86U1J3P5BV9EHexjvXda416D4wHAFdxUhUzjKj42CNM4TYTrrsXRT4m_fMNq78NrvwMf7ge2tmcSYNf04c7gqInQzJMNiKILZbQXN0yxExZ1lBbPesg-ZCsx5HZ1544-g0yrcZvxu7HkSwIG56C3ITae51rtMj4lpxyYUxdR9MZ0JZ-HH2XlCT_F3BMDUn_IHNXj2IDF6gI-1kx3UWwYZ5uCyTipbsuOwgFCINFA2m8h3IM0jS9KXGLNrixaej9M0uDEcYkxVRvSwNKJfeHmnhJefYEk82192XpmXJDft8Q", secret)
    console.log(decoded)
  }
});

export const config = {
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};

I'm using jose to verify the JWT token. However, upon calling the middleware, I encounter an error:

Promise {
  [Symbol(async_id_symbol)]: 290979,
  [Symbol(trigger_async_id_symbol)]: 290975,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: undefined,
  [Symbol(kResourceStore)]: {
  headers: [Getter],
  cookies: [Getter],
  mutableCookies: [Getter],
  draftMode: [Getter]
}
}
TypeError: Key for the RS256 algorithm must be of type CryptoKey. Received an instance of Uint8Array

Any idea what might be causing this issue?

Answer №1

To utilize the jose library effectively, follow these instructions. Start by examining your JWT to extract the algorithm specified in the header and the issuer/audience information from the payload:

import {createRemoteJWKSet, jwtVerify} from 'jose';

const jwksUri = 'https://api.clerk.dev/v1/jwks';
const jwks = createRemoteJWKSet(new URI(jwksUri));

async function validateJWT(accessToken: string): Promise<JwtClaims> {

  const options = {
    algorithms: ['RS256'],
    issuer: 'myissuer',
    audience: 'myaudience'
  };

  const result = await jwtVerify(accessToken, jwks, options);
  return result.payload
}

On the initial call to validateJWT, the library will retrieve token signing public keys and store them in a cache. This simplifies your code and ensures its resilience, even when clerk updates its token signing keypair.

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

Understanding the Class Syntax in Node.js

I'm having trouble understanding how to retrieve the value from a Node JS Class [Trying to use [Symbol.iterator '']]alert(Hello, ${this.name}!); Is there another way to approach this? class User { name = "Anonymous"; sayHi() { ...

Automatically inserting a row into an HTML table

My table structure looks like this: <form name="frm_data_nasabah2" method="post" enctype="application/x-www-form-urlencoded" action="<?php echo $page_action;?>"> <table class="table table-bordered table-hover" id="tab_logic_ ...

What is the best way to update my logo and incorporate a colored border at the bottom of my fixed header while the user is scrolling down?

After spending countless hours researching online, I've been struggling to implement header effects on scroll without using JavaScript. My goal is to achieve a simple effect where the header reduces in height, the logo changes, and a colored border is ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...

Utilizing React with Material UI, implement a Select component while disabling the scroll lock and ensuring the menu is positioned relative to

import React from "react"; import "./styles.css"; import Input from "@material-ui/core/Input"; import MenuItem from "@material-ui/core/MenuItem"; import FormControl from "@material-ui/core/FormControl"; import Select from "@material-ui/core/Select"; cons ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

Getting an error message like "npm ERR! code ENOTFOUND" when trying to install Angular CLI using the command "

Currently, I am eager to learn Angular and have already installed Node version 18.13.0. However, when attempting to install Angular CLI using the command npm install -g @angular/cli, I encountered an issue: npm ERR! code ENOTFOUND' 'npm ERR! sys ...

Tips for maintaining a user's session post-login with Passport and Express JS

I recently set up a node backend using express and integrated Passport for authentication purposes. My application has a route called /login for logging in and another route called /me to retrieve information about the currently logged in user. Below is t ...

Packages required for plugins on Npm

I am fairly new to NPM dependencies and I'm currently transitioning from the Ruby world. Working on a Chrome extension utilizing React, in my content.js script, I have the following code at the top: var React = require("react"); var $ = require("jqu ...

Best practices for implementing Django backend authentication with NextJS frontend forms

I've created an API hub using Django and a frontend application with NextJS. Currently, I'm working on implementing authentication from the NextJS app to the Django API and I'm seeking advice on best practices. At the moment, the NextJS app ...

Is it possible to delete an element from an HTML form?

I'm facing an issue with removing an element from my HTML form during the loading process. The specific element in question is as follows: <input type="hidden" name="testToken" value="1000ad"></input> Here's what I've tried so ...

Items seem to vanish into thin air and become immovable when attempting to relocate them

I am attempting to create a unique grid layout with 3x3 dimensions, where each grid item represents a fragment of a single image. These items should have the capability to be dragged and dropped inside another 3x3 grid, in any desired sequence. I have hit ...

Error encountered: Difficulty rendering Vue 3 components within Google Apps Script

Currently delving into Vue and Vue 3 while coding an application on Google Apps Script. Following tutorials from Vue Mastery and stumbled upon a remarkable example by @brucemcpherson of a Vue 2 app functioning on GAS, which proved to be too challenging in ...

What is the process for generating Json using information from a form?

Recently, I embarked on a project that involves creating online tours via a form filled out by the administrator. The data submitted through the form is then mapped into a Mongoose Schema and transformed into JSON. In the createcontent.js file, I utilized ...

Avoiding HTML (JSX) tag duplication in React Component

Having the same code in my React component multiple times is becoming repetitive and inefficient. Is there a way to follow the DRY principle and avoid repeating this code? While creating a landing page with Sass styling, I noticed that I am duplicating t ...

What are some strategies for efficiently displaying a large amount of data on a screen using Javascript and HTML without sacrificing performance?

Imagine having a hefty 520 page book with over 6,200 lines of text ranging from 5 to 300 characters each. The challenge lies in efficiently displaying this content on the screen for users to read without causing lag or performance issues. Attempting to re ...

Getting the checkbox count value in a treeview upon successful completion of an AJAX request

After successful JSON Ajax response, a treeview structure with checkboxes is displayed. I need to capture the number of checkboxes checked when the save button is clicked. @model MedeilMVC_CLOUD.Models.UserView <script type="text/javascript"> ...

Strategies for triggering a refresh in Next.js 13 and updating data directly from the database

I am currently in the process of developing a subscription-based web application with Next.js 13. Users have the ability to manually end their Free Trial and transition to a Premium subscription, which is then reflected as their current plan on the client- ...

Unable to read a QR code from a blob link

After spending countless hours searching Google and SO, I still haven't found a solution on how to scan a QR code in my Java based Selenium tests. I've tried various methods but encountered errors along the way. Attempted to use the ZXing libr ...

Enhancing Real-time Communication with NodeJS and NowJs Servers

Recently, I stumbled upon NodeJS and NowJS and I'm fascinated by the technology. My goal is to develop a Facebook-style instant commenting application where users can post comments that will instantly appear on the feed. After watching the screencast ...