2016-02-13 305 views
1

我已经看过这个堆栈溢出条目Node.js - Express.js JWT always returns an invalid token error in browser response,但我找不到解决方案。JWT返回无效签名错误,即使我在授权中输入令牌

我试图编写一个小节点应用程序作为使用JWT访问令牌的概念验证。我去了http://jwt.io/并试图跟随视频教程。我得到了一个生成的令牌,但实际上使用该令牌时,出现“UnauthorizedError:invalid signature”错误。下面是我的源代码

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}!`); 
}); 
+0

我想通了这个问题。我有不匹配的秘密。我有一个'wutangclan'的秘密和'36间商会'的秘密。他们都需要保持一致。我在app.post到/ shaolin的路径中也有空间。解决这两个问题后,一切正常。 – flipvinyl

回答

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

你的秘密是 '武当帮' ,这里

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

你的秘密是'36室