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

Is there a way to stop a music track from playing?

function playMusic(){ var music = new Audio('musicfile.mp3'); if (music.paused) { music.play(); } else { music.pause(); } } <input type="button" value="sound" onclick="playMusic()" ...

Issue with Electron dialog.showOpenDialog() Filters malfunctioning

Recently, I've been working on a modified version of an IDE on GitHub and encountered a major issue where the files were being saved to cookies instead of the computer. This prompted me to find a way to save and open files efficiently. While I managed ...

Create an interactive webpage that automatically generates new HTML elements after retrieving JSON data from a Web API during page load

I am currently in the process of developing a hybrid Android App using Phonegap/Apache Cordova. The main function of my app is to retrieve data from my web API, which is being served through JSON. I have implemented the following code snippet for this task ...

Add a click function to an element in a grid when it is databound

In my TypeCtrl ES6 class angular controller, I am using a kendo datagrid directive with a template for grid config options. Within the grid template, I need to call a method from the TypeCtrl class when a span within the row is clicked. However, the functi ...

Copying JSON Data in JavaScript: A Guide

Seeking advice on how to duplicate JSON within the same JSON at various hierarchy levels. Take a look at this example JSON below: Initial code snippet looks like this: { "data": { "moduleName": { "content": { "modul ...

Pass the array data stored in React state over to Node/Express

I have been exploring ways to transfer an array from my react front end to my node/express back end. Initially, I attempted the following method. In React: saveUpdates = (clickEvent) => { var list = []; var length = this.props.title.length; ...

Why does the shadow in Three.js only appear in a limited region?

I brought in a model and noticed that the shadow is only visible in a small area (highlighted in green in the image). How can I make all objects display their shadows? https://i.sstatic.net/hmzp2.png Below is my code snippet. light = new THREE.Direction ...

The Angular material datepicker is not accurately capturing the date I am trying to select

I am facing an issue with the Angular Material datepicker where it does not select the date I choose. Instead, in my AngularJS controller, I always get the sysdate even if I select another date. Can anyone help me figure out what I am doing wrong? Here is ...

Tips for filtering data using an array within an object containing arrays

Below is the provided information: userRoom = ['rm1']; data = [{ name: 'building 1', building: [{ room: 'rm1', name: 'Room 1' },{ room: 'rm2', name: ' ...

Guide on accessing the text content within a div element in HTML by triggering a button click

To extract specific text from multiple div tags, I need to trigger an event when clicking a button. <div class="col-lg-3 col-md-6 mb-4"> <div class="pricing-table pricing-secondary"> <div class="price-hea ...

Error: Selenium-Javascript tests encountering an unexpected token issue

Having worked with Selenium using Java for a long time, I decided to switch gears and start writing Selenium scripts in JavaScript. I found a helpful guide to learn JavaScript with Selenium, which you can check out here. However, when I attempted to run n ...

Is it possible for a popup to appear without any user interaction

Do you ever wonder how certain websites are able to trigger pop-ups without being blocked by Chrome's pop-up blocker? I had always thought that pop-up blockers only allowed window.open if it was initiated by a user action. However, the situation seem ...

A single click causes the entire row of cards to extend seamlessly

The cards on this tab were generated using a loop and the data is sourced from a database. When I click on the "Show More" button, the entire visible column expands along with it. The expansion does not reveal the content immediately; instead, the content ...

Obtaining the following class name from elements

I am struggling with extracting classes from a block of HTML code: <div class="container"> <div class="item first">...</div> <div class="item second">...</div> <div class="item third">...</div> <div cla ...

Is Proxy.apply() not functioning correctly on Node.js? I'm unsure if this is a bug or if I am implementing it incorrectly

Utilizing a Proxy object has been quite helpful for me. The getter and setter functions are working perfectly as expected. However, I have encountered an issue where the apply method is never invoked. var p = new Proxy({}, { /* getter */ get(t ...

Displaying asynchronous promises with function components

Apologies if this post appears duplicated, I am simply searching for examples related to class components. Here is the code snippet I am working with: export const getUniPrice = async () => { const pair = await Uniswap.Fetcher.fetchPairDat ...

Error: authentication failed during npm installation due to an incorrect URL

After executing npm install @types/js-cookie@^2.2.0, an error occurred: npm install @types/js-cookie@^2.2.0 npm ERR! code E401 npm ERR! Unable to authenticate, need: Basic realm="https://pkgsprodsu3weu.app.pkgs.visualstudio.com/" npm ERR! A com ...

Steps for Adding a class or Id to an Ext.Msg.alert box

Is there a way to customize the style of a specific Ext alert box without affecting all alert boxes? Can someone please explain how to assign a class or ID to an Ext.Msg.alert box? Ext.Msg.alert('Status', 'Changes saved successfully.' ...

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

Understanding ExpressJS: Exploring the distinctions between ?, +, * in string patterns and regular expressions

Hello there! As a newcomer to Express, I've been on the hunt for a thorough explanation of string patterns with no luck. The path-to-regexp documentation has left me scratching my head. In particular, I'm grappling with this somewhat enigmatic s ...