Error encountered while attempting to validate JWT

This question has been asked multiple times, but I'm still struggling to find the root cause of the issue. I have already signed some data with a token, but when I attempt to verify it, I receive an error message saying "jwt malformed". Interestingly, both the token received from the authheader and the "secret token" specified in my dotenv file appear identical: the token from the authheader is

1e0af40b5849caa62d2bd4a65fddc832b027034fe656d50003b86e1417af6491c944b9ed936e5090d114a4c81aa09754d920daa58736f3ba6d49977cc271a0dd
, and the token in the dotenv file is also
1e0af40b5849caa62d2bd4a65fddc832b027034fe656d50003b86e1417af6491c944b9ed936e5090d114a4c81aa09754d920daa58736f3ba6d49977cc271a0dd
. Doesn't the jwt verify method only compare whether the two strings match? Do I need additional configuration in the signing method, such as specifying the signing algorithm or type? Below is my middleware code for verification:

function authenticateToken(req , res , next){
  const authHeader = req.headers.authorization;
  const token = authHeader && authHeader.split(' ')[1]
  console.log(token)
  if(token == null) return res.status(401).send()
  
    jwt.verify(token , process.env.ACCESS_TOKEN_SECRET , (err , user)=>{
      console.log(process.env.ACCESS_TOKEN_SECRET)
      console.log(err)
    if(err) {return res.status(403).send()}
    console.log(err)
    req.new_user = user;
    
    next()
  })
}

The following code returns a value after verification :

  isLoggedIn(app ,db){
    app.get('/isLoggedIn'  , authenticateToken, async(req ,res)=>{
    await db.query('select * from client where username = $1' , [req.new_user.name] , (err , data)=>{
      res.json(data.rows[0])
    })
    
    
    })
  }

I don't believe the issue lies within this part of the code since:

logging_auth(app ,db){
    app.post('/logging_auth' , async(req ,res)=>{
      let credential = req.body
      let email = credential.login_email;
      let password = credential.login_password
      let email_cols = [email];
      await db.query('select client_password  , username from client where email = $1' , email_cols , async(err , data)=>{
        if(data && data.rows.length === 0){
          res.json({
            success : false,
            msg : 'email or password does not exist'
          })
        }
        if(data && data.rows.length === 1){
          bycrypt.compare(password , data.rows[0].client_password , (bcrypterr , verified)=>{
            //if verified gives token
            if(verified){
              const new_user = {name : data.rows[0].username}
              jwt.sign(new_user , process.env.ACCESS_TOKEN_SECRET)
              res.json({access_token :  process.env.ACCESS_TOKEN_SECRET , success : true , use:new_user.name})
            }else{
              console.log(bcrypterr)
            }
            //else response success false
          })
        }
        if(err){
          res.json({
            success : false,
            msg : 'Opps Something Went Wrong',
            status : 501
          })
        }
      })
    })

  }

The error only occurs during the verification process.

Answer №1

The problem lies in the code snippet you provided. It seems that you are inadvertently exposing your JWT private key. When using `jwt.sign()`, it actually returns a JWT, so consider revising the lines of code like this:

const access_token = jwt.sign(new_user, process.env.ACCESS_TOKEN_SECRET)
res.json({access_token, success: true, user: new_user.name})

After making these adjustments, your response should include a token structured as follows: xxxxx.yyyyy.zzzzz, with x representing the header, y standing for the payload (which contains your user data), and z being the signature.

If you want to learn more about how JWTs are structured, visit JWT.io.

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

Command in Selenium Webdriver for initiating a mouse click

Currently, I am in the process of writing tests for a Java application that has been created with the Vaadin framework. To conduct these tests, I have opted to utilize the Robot Framework. In certain instances, I must implement robot framework commands suc ...

Unable to utilize the resolved value received from a promise and returned from it

Within the code snippet below, I am retrieving a Table object from mysql/xdevapi. The getSchema() and getTable() methods return objects instead of promises. The purpose of this function is to return a fulfilled Table object that can be used synchronously i ...

The significance of Token Details in Tokbox

I'm currently working on developing a video chat platform that caters to various user roles - some may just observe while others actively participate in calls. I've been exploring the capabilities of the Tokbox Api () which allows metadata to be ...

Ways to prevent a loop from constantly restarting

After clicking the generate ID button once, it will become disabled and display a set of numbers. The last 4 digits are in a loop sequence starting with "0001". If I were to re-enable the generate ID button and click it again, the last 4 digits would incre ...

The CSS and JS codes are not successfully integrating into the webpage

I am encountering an issue with loading CSS and JS files onto my page. My project involves PHP and Xampp. The file structure is as follows: My Site - CSS - index.css - JS - index.js - Index.php (Apologies for the lack of a folder tre ...

What is the most effective way to manage and respond to multiple events while also organizing the overall structure of

I am currently in the process of planning a complex web application using WebGL and Three.js. As I experiment with different tests, I have encountered a problem that is raising many questions for me. I am unsure of the correct approach to take and would gr ...

How to display images conditionally on the server side using Next.js

I think I may have the answer already, but I thought I'd check if anyone has a different solution. I'm working on a hero banner with one image for mobile and a different one for desktop display. Normally, I would use conditional rendering, but ...

All shadows in the THREE.js scene are perfectly aligned

I have taken a mix of examples from the three.js documentation and included the mesh.castShadow = true property on the meshes generated from the Glitch post-processing example. However, upon checking the jsfiddle link provided below, it's noticeable t ...

What is the best way to implement onChange for multiple form fields in Reactjs?

Can anyone help me troubleshoot my form? I'm having issues with typing into the fields and nothing happens when I try. Initially, whatever text I input would show up in all the fields simultaneously, but after making some changes, it stopped working ...

What is the process for retrieving the updated document from the findOneAndUpdate function?

Utilizing MongoDB with Node.js, I installed the MongoDB module using npm install mongodb. I encountered an issue where updating an existing document did not return the updated document; instead, it returned the original one. Even after setting the returnN ...

"Troubleshooting an issue with ng-model not functioning properly with radio buttons in Angular

I'm a newcomer to Angular and I'm attempting to retrieve the value of the radio button selected by the user using ng-model. However, I'm not seeing any output in "selected contact". Check out My HTML below: <!doctype html> <html n ...

What is the best way to upload a file in Node.js using Express and Multer?

When attempting to send a file from the front end to my node js server, I encountered an issue with receiving the file on the back end. Here is the code snippet: <form id="file-upload-form" class="uploader" action="/uploa ...

How can I find the URL of a webpage that is not showing up in the search bar? Utilize Google Instant

I'm currently working on an extension and I've encountered a challenge... I'm trying to figure out how to extract the URLs from a Google instant search page. The browser's URL bar doesn't seem to update instantly, so I'm unsur ...

Using @carbon/react in conjunction with Next.js version 13 leads to unconventional styling

Here's what I did to set up my Next.js application: npx create-next-app@latest I then installed the necessary package using: npm i -S @carbon/react The global styles in app/globals.scss were customized with this code snippet: @use '@carbon/reac ...

restrict the maximum character count in regex

The string can consist of a single number or multiple numbers separated by "-", but the total character count must not exceed 6. Examples of valid strings 5 55-33 4444-1 1-4444 666666 Examples of invalid strings -3 6666- 5555-6666 My initial regex / ...

Change from one value to another using a decaying sinusoidal wave

Can someone help me come up with a formula that will smoothly transition from a starting value to an end value over a specified time using a Sin or Cos wave? I'm attempting to replicate a bouncing effect like the one shown in my sample using CSS and ...

How to detect a click event in any area of an Angular2

Hey there, I'm new to typescript and angular 2 and I've encountered an error in my code. Can someone lend me a hand in fixing this? import { Component, HostListener } from '@angular/core' export class TooltipComponent { public sh ...

add the closing </div> tag using jquery only

Having a slight issue here, it seems that jQuery is being overly clever. Within my HTML code, I am attempting to insert this string into a div container: </div><div class="something"> You'll notice that the closing tag comes first, foll ...

Having trouble with images not showing up on React applications built with webpack?

Hey there! I decided not to use the create react app command and instead built everything from scratch. Below is my webpack configuration: const path = require("path"); module.exports = { mode: "development", entry: "./index.js", output: { pa ...

Would you say the time complexity of this function is O(N) or O(N^2)?

I am currently analyzing the time complexity of a particular function. This function takes a string as input, reverses the order of words in the string, and then reverses the order of letters within each word. For example: “the sky is blue” => ...