问题
I've checked many answers on the internet but I think I'm doing some other mistake also. My question is strictly related to guarding /contribute
route using JWT (which is a POST request). My API is in expressjs
. First I hit /login
route with correct credentials and get a token. This token I cross checked on jwt.io and it says "Invalid Signature".
Here is that token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJqZWN0IjoiNWVhZDlkOGY4N2VjMjkwMDE3YzRkODkzIiwiaWF0IjoxNjA3ODczNjY2fQ.H5RI-lOBzfJo4_FgParuJA4ULnJ_An6uihiF31bzNtU
Then I would hit /contribute
route with the same token. Here is my code:
api.js
const express = require('express');
const router = express.Router();
...
const jwt = require('jsonwebtoken');
...
router.post('/login', (req, res) => {
let userData = req.body
User.findOne({ email: userData.email }, (error, user) => {
if (error) {
console.log(error)
} else {
if (!user) {
res.status(401).send('Invalid email')
} else if (user.password !== userData.password) {
res.status(401).send('Invalid password')
} else {
let payLoad = { subject: user._id }; // tried { subject: 'foobar' } also
let token = jwt.sign(payLoad, 'secretKey');
res.status(200).send({ token, userData, user });
}
}
})
})
router.post('/contribute', verifyToken, (req, res) => {
console.log('Pushing new article');
let userPost = req.body;
let post = new Post(userPost);
post.save((error, registeredPost) => {
if (error) {
console.log(error);
} else {
res.status(200).send(registeredPost);
}
})
})
function verifyToken(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send('Unauthorized request')
}
let token = req.headers.authorization.split(' ')[1];
if (token === 'null') {
return res.status(401).send('Unauthorized request')
}
let payload = jwt.verify(token, 'secretKey')
if (!payload) {
return res.status(401).send('Unauthorized request')
}
req.userId = payload.subject
next()
}
module.exports = router;
But the moment I hit /contribute
I get this:
JsonWebTokenError: jwt malformed at Object.module.exports [as verify] (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\jsonwebtoken\verify.js:63:17) at verifyToken (C:\Users\320050772\Documents\socialcoderapinodejs\routes\api.js:86:23) at Layer.handle [as handle_request] (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\320050772\Documents\socialcoderapinodejs\node_modules\express\lib\router\layer.js:95:5)
Please point out my mistake.
I checked on Postman also. Token is generated but again it is invalid. Why my code is generating invalid tokens.
回答1:
It been noticed that Generated Token is valid. But its not been reaching to backend with upcoming next call e.g Post of /contribute. showing some non-valid value. Therefore, let the valid token to be arrived on Backend so that jwt.varify could validate it correctly.
回答2:
Bro I checked your code, all is OK, verifyToken
✅ , (though not the User and Post objects) make sure you send the authorisation header correctly like this:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJqZWN0IjoiMTIzNDQ1IiwiaWF0IjoxNjA3ODgwMjkwfQ.zJbcqM8yBRABxhm5BgQNow1gmzsgUjiLdPdv7Tq5ND4
I used the code from your example and modified a bit
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.get('/', (req, res) => res.send('123'));
app.post('/login', (req, res) => {
let payLoad = { subject: '123445' };
let token = jwt.sign(payLoad, 'secretKey');
res.status(200).send({ token });
});
app.post('/contribute', verifyToken, (req, res) => {
res.send('i can reach here...');
});
function verifyToken(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send('Unauthorized request');
}
let token = req.headers.authorization.split(' ')[1];
if (token === 'null') {
return res.status(401).send('Unauthorized request');
}
let payload = jwt.verify(token, 'secretKey');
if (!payload) {
return res.status(401).send('Unauthorized request');
}
req.userId = payload.subject;
next();
}
app.listen(3000, () => console.log('server on 3000'));
来源:https://stackoverflow.com/questions/65277469/jsonwebtokenerror-jwt-malformed-creating-an-api-in-expressjs