2016-02-13 78 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室