我正在尝试使用 jsonwebtoken npm 使用以下代码片段验证和解码 json Web 令牌:
var jwt = require('jsonwebtoken');
var fs = require('fs');
var encoded = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJsb2dpbklkIjoicm9vdCIsInVzZXJOYW1lIjoicm9vdCIsInJvbGUiOiIwIiwic3RhdHVzIjoiMSIsInBhc3N3b3JkIjoiYWNiM2UxNDFkODgzMTA2ZGUyZjMwZDQ2ZTc2YzA5Y2YiLCJuYW1hayI6InJvb3QiLCJsYXN0TG9naW5UaW1lIjoibnVsbCIsImVtYWlsIjoicm9vdEBlY3AuY29tdml2YS5jb20iLCJjb250YWN0Tm8iOiIwMTIzNDU2Nzg5IiwiYXV0aFR5cGUiOiJudWxsIiwicGFyZW50SWQiOiJudWxsIiwibGFuZ3VhZ2UiOiJudWxsIiwiY3VycmVuY3kiOiJudWxsIiwiYWN0aXZhdGlvbkR0IjoibnVsbCIsImV4cGlyeUR0IjoibnVsbCIsImRlbGV0ZWRBdCI6Im51bGwiLCJwZXJtcyI6IntcIiVcIjo3fSIsImJhbGFuY2UiOiIxMjk5IiwiY2FjaGVkIjp0cnVlLCJpYXQiOjE0NTcxMDA5MjZ9.yn2Vb3hE7BKrXntCa-pTVAS7MwsaHD1csPZMiibOhwk';
fs.readFile('/etc/jwt/shared.key', function(err, result){
if (err) {
console.error("error:", err);
return;
}
var verified = jwt.verify(encoded, 'ssshhhh');
//var verified = jwt.verify(encoded, result);
console.log("verified:", verified);
});
当我尝试使用硬编码值 jwt.verify() 时,程序失败
if (err) throw err;
^
JsonWebTokenError: invalid signature
at Object.JWT.verify (/home/rvnath/projects/comviva/mbs/ecp7/dev/authserver/node_modules/jsonwebtoken/index.js:219:17)
at /home/rvnath/projects/comviva/mbs/ecp7/dev/authserver/testverify.js:11:22
at fs.js:334:14
at FSReqWrap.oncomplete (fs.js:95:15)
但是,如果我读取密钥文件(而不是硬编码)并提供给验证功能,它就可以正常工作。在这种情况下,程序的输出如下:
rvnath@rv ~/projects/comviva/mbs/ecp7/dev/authserver $ node testverify.js
verified: { id: '1',
loginId: 'root',
userName: 'root',
role: '0',
status: '1',
password: 'acb3e141d883106de2f30d46e76c09cf',
namak: 'root',
lastLoginTime: 'null',
email: 'root@ecp.ecp.com',
contactNo: '0123456789',
authType: 'null',
parentId: 'null',
language: 'null',
currency: 'null',
activationDt: 'null',
expiryDt: 'null',
deletedAt: 'null',
perms: '{"%":7}',
balance: '1299',
cached: true,
iat: 1457100926 }
我的秘密文件是一个简单的文本文件,如下所示:
rvnath@rv ~ $ cat /etc/jwt/shared.key
ssshhhh
rvnath@rv ~ $
总之,我正在尝试使用与文件 /etc/jwt/shared.key 中存储的相同密钥进行解码,但是当密钥值在程序中硬编码时它会失败。我在这里做错了什么?
编辑 jwt 是由我的服务器应用程序生成的,方法是从同一文件中读取密钥:
/** Creates a signed JSON WEB TOKEN **/
function createJWT(user) {
return fs.readFileAsync('/etc/jwt/shared.key').then(function(cert){
var secret = cert.toString();
console.log("shared secret:", secret);
var token = jwt.sign(user, secret);
//console.log("token verification:",jwt.verify(token, cert));
return token;
});
}