Json Web Token verify() return jwt malformed
Asked Answered
C

9

26
const jwt = require("jsonwebtoken");
const SECRET = "superSuperSecret";

module.exports = function(req, res, next) {
    const token = req.body.token || req.query.token || req.headers[ "x-access-token" ];
    if (token) {
        return jwt.verify(token, SECRET, function(err, decoded) {
            if (err) {
                return res.json({
                    success: false,
                    message: "Failed to authenticate token.",
                });
            }
            req.user = decoded;
            return next();
        });
    }
    return res.unauthorized();
};

I'm using Postman to test my API. I setup the header with a x-access-token key and the value superSuperSecret. I got the error {"name":"JsonWebTokenError","message":"jwt malformed","level":"error"}. I'm using this https://github.com/FortechRomania/express-mongo-example-project/blob/master/src/middlewares/validateToken.js

Chester answered 14/8, 2018 at 20:5 Comment(3)
What is the value of token you are getting after console?Denationalize
@SookieSingh superSuperSecretChester
Also I think that jwt.verfy with a callback is a async functionAltostratus
D
41

You cannot pass any value as token. You need jwt.sign() to create a token. Look at the documentation of JWT for more information.

Also,

For the request Header name just use Authorization not x-access-token. Place Bearer before the Token.

Authorization: Bearer TOKEN_STRING

Each part of the JWT is a base64url encoded value. You can get your token as:

var token = req.headers.authorization.split(' ')[1];
Denationalize answered 14/8, 2018 at 20:21 Comment(3)
what is TOKEN_STRING?Hamo
Can you please look into my issue here: #65277969Clerkly
@TM TOKEN_STRING is the JWT(JSON Web Token) you get from the server after you log in to the system. For every request, you send from the client to the server(only for protected routes) you will have to append the token in the Authorization header so the server knows that the request is an authenticated request.Anglonorman
E
15

Note :

JWT will return jwt malformed If Token is null/Invalid-Signature that is being passed to jwt.verifty function

let token = null;
let payload = jwt.verify(token, 'secretKey'); // ERROR : jwt malformed

Eupheemia answered 31/10, 2019 at 10:30 Comment(6)
I'm having the same issue and I need your help.Clerkly
See this is my code: let payLoad = { subject: user._id }; let token = jwt.sign(payLoad, 'secretKey');Clerkly
@Clerkly can u share your code (middleware), I want to see, in order to help?Eupheemia
Yes sure. Here it is: github.com/tmtanzeel/socialcoderapinodejs/blob/main/routes/…Clerkly
Here I've opened a question: #65277969Clerkly
@Clerkly I have tested your code by running on local server, and figure out the problem mentioned there #65277969Eupheemia
A
5

From what I see, you are not sending the actual JWT token but the secret instead. A valid JWT token consist of a three-part string delimited by dots, like so:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

https://jwt.io/

As you can see on the above website, 'superSuperSecret' is not a valid JWT token.

Alfie answered 14/8, 2018 at 20:22 Comment(1)
Then what is the solution. My code is also generating the same token. This code I have: let payLoad = { subject: user._id }; let token = jwt.sign(payLoad, 'secretKey'); res.status(200).send({ token, userData, user });Clerkly
S
2

From client side token can be passes as null or blank string, then this error will genrated.

Savonarola answered 17/11, 2021 at 9:5 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Tenorio
C
1

The same problems seems in my case due to invalid token format. A token consists of three parts: Header, payload and signature separated by dot (.).

In my case, i am using token like this: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9_eyJpZCI6IjY0NzcxYjg2YTQ4MGY2MTI3NDk3ODRhOCIsImlhdCI6MTY4NTUyNzQzMCwiZXhwIjoxNjg1NTI3NzMwfQ_WNToTRU6H5Qm30S0xH3cjU1LK9l8IAejXVrd2XdSMRw

Which is totally stupid error in my case. Instead of using _ this separator i have to use dot . as a separator
(header.payload.signature)
for correct format. so jwt.verify() can handle this.
I hope you understand what causes an error.

Note: If there is more underscore _ on your token then during conversion of _ to . also leads you on problem.

Cathe answered 31/5, 2023 at 10:9 Comment(0)
D
0

Token consists of 3 parts delimited by dots. There is a code from jsonwebtoken below

var parts = jwtString.split('.');

if (parts.length !== 3){
  return done(new JsonWebTokenError('jwt malformed'));
}
Definitive answered 14/2, 2022 at 21:55 Comment(0)
A
0

This problem usually stems from when the value of JWT isn't available to be read at all. Check and make sure the token is available at all; maybe on the environment variable on your postman or any other API testing software you're using

Aleedis answered 29/12, 2022 at 11:47 Comment(0)
N
0

Postman router from which is return jwt malformed, go to test options and skip pm.environment.set("jwt", pm.response.json().token);

Nipha answered 12/8, 2023 at 8:13 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Tenorio
A
0

The verification of token is not possible if token is not assigned.

function getUser(token){
    if(!token) return null;
    try {
    return jwt.verify(token ,secret);
        
    } catch (error) {
        return null;
    }
}
Aphra answered 26/2 at 12:5 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Tenorio

© 2022 - 2024 — McMap. All rights reserved.