admin管理员组

文章数量:1287878

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 / 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 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}!`);
});
Share Improve this question edited May 23, 2017 at 11:45 CommunityBot 11 silver badge asked Feb 13, 2016 at 0:56 flipvinylflipvinyl 411 gold badge1 silver badge3 bronze badges 1
  • I figured out the problem. I had mismatched secrets. I had a secret of 'wutangclan' and a secret of '36 chambers'. They both need to be the same. I also had a space in the path int he app.post to /shaolin. After fixing both issues everything works fine. – flipvinyl Commented Feb 13, 2016 at 1:15
Add a ment  | 

3 Answers 3

Reset to default 4

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.

app.use(expressJWT({ secret: 'wutangclan' }).unless({ path: ['/', '/login', '/wutangclan'] }));

your secret is 'wutangclan' , and here

let myToken = jwt.sign({username: req.body.username},  '36 chambers');

your secret is '36 chambers'

You should keep your SECRET same sometimes it missing a word

exports.signin=(req,res)=>{
    const {email,password}= req.body;

    const errors = validationResult(req);

    if(!errors.isEmpty()){
        return res.status(422).json({
            error: errors.array()[0].msg
        })
    }

    User.findOne({email},(err, user)=>{
        if(err || !user){
            return res.status(400).json({
                error: "user does not exists"
            })
        }

        if(!user.authenticate(password)){
            return res.status(401).json({
                error:"Email and password do not match"
            })
        }

        // create a token

        const token= jwt.sign({_id:user._id}, process.env.SECRET);

        // put a token into a cookie
        res.cookie("token", token,{expire: new Date() + 9999});
        // res.send()

        // response to front end
        const {_id,name, email, role}= user;
        return res.json({token, user: {_id,name,email,role}})

    })
}

// protected routes
exports.isSignedIn = expressJwt({
    
    secret: process.env.SECRET,
    
    userProperty: "auth"
})

本文标签: javascriptJWT Returns Invalid Signature Error Even When I enter the token in AuthorizationStack Overflow