I already looked at this stack overflow entry Node.js - Express.js JWT always returns an invalid token error in browser response but I couldn't find a solution there.
I have attempted to write a small node app as a proof of concept for using JWT access tokens. I went to http://jwt.io/ and attempted to follow along with the video tutorial. I got as far as getting a token generated but when it came to actually using the token, I get a "UnauthorizedError: invalid signature" error. Below is my source code
const myUsername = 'ironflag';
const express = require('express');
const expressJWT = require('express-jwt');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const PORT = 2000;
// App
const app = express();
//fake data
let killerBeez = {
members: 9,
location: 'staten island',
stateOfBeing: 'wu-tang forever',
memberList: [
{
name: 'RZA',
alias: ['Bobby Steels', 'Prince Raheem', 'Bobby Digital', 'The Abbot']
},
{
name: 'GZA',
alias: ['The Genius','Drunken Monk']
},
{
name: 'Ol\' Dirty Bastard',
alias: ['Big Baby Jesus', 'Dirt McGirt', 'Ason Unique']
},
{
name: 'Inspecta Deck',
alias: 'Rebel INS'
},
{
name: 'Raekwon the Chef',
alias: 'Lex Diamond'
},
{
name: 'U-God',
alias: 'Baby U'
},
{
name: 'Ghostface Killah',
alias: ['Tony Starks', 'Big Ghost', 'Ironman']
},
{
name: 'Method Man',
alias: ['Johnny Blaze', 'Iron Lung']
},
{
name: 'Capadonna'
}
]
};
app.use(bodyParser.urlencoded());
app.use(expressJWT({ secret: 'wutangclan' }).unless({ path: ['/', '/login', '/wutangclan'] }));
app.get('/', function (req, res) {
res.send('Hello world\n');
});
app.get('/wutangclan', function (req, res) {
res.send(killerBeez);
});
app.post('/login', function (req, res) {
if(!req.body.username || myUsername !== req.body.username) {
res.status(400).send('username required');
return;
}
let myToken = jwt.sign({username: req.body.username}, '36 chambers');
res.status(200).json({token: myToken});
});
app.post('/shaolin ', function (req, res) {
if(req.body.location) {
killerBeez.location = req.body.location;
res.status(200).send('location updated');
} else {
res.status(400).send('location required');
}
});
app.listen(PORT, function () {
console.log(`Example app listening on port ${PORT}!`);
});
I had the same issue when I tried to integrate the Auth0 authentication in my NodeJS application. I used the express-jwt module for the access token authentication and I got the invalid signature
error. In my case I used a wrong client secret. I used the secret to a created application but the correct secret on the server side must be the API secret instead. So check your credentials, the secret to generate the token must be the secret to the API.