JWT解码返回null
JWT decode returns null
我是Node.js的新手,正在阅读Fabian Cook的Node.js Essentials。当尝试使用JWT进行身份验证时,我从JWT.decode(令牌)中得到了一个NULL,但该令牌可以由JWT.io上的调试器解析。代码出了什么问题?
var Passport = require( 'passport' );
var LocalStrategy = require( 'passport-local' ).Strategy;
var Express = require( 'express' );
var BodyParser = require( 'body-parser' );
var jwt = require( 'jsonwebtoken' );
var Crypto = require ( 'crypto' );
var users = {
zack: {
username: 'zack',
password: '1234',
id: 1,
},
node: {
username: 'node',
password: '5678',
id: 2,
},
}
var localStrategy = new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
},
function(username, password, done) {
user = users[ username ];
if ( user == null ) {
return done( null, false, { message: 'Invalid user' } );
};
if ( user.password !== password ) {
return done( null, false, { message: 'Invalid password' } );
};
done( null, user );
}
)
Passport.use( 'local', localStrategy );
var app = Express();
app.use( BodyParser.urlencoded( { extended: false } ) );
app.use( BodyParser.json() );
app.use( Passport.initialize() );
var generateToken = function( req, res ) {
var payload = {
id: user.id,
username: user.username
}
var secret = user.secret || Crypto.randomBytes( 128 ).toString( 'base64' );
var token = jwt.sign( payload, secret );
user.secret = secret;
return token;
};
var generateTokenHandler = function ( req, res ) {
var user = req.user;
var token = generateToken( user );
res.send( token );
};
app.post(
'/login',
Passport.authenticate( 'local', { session: false } ),
generateTokenHandler
);
var BearerStrategy = require( 'passport-http-bearer' ).Strategy;
var verifyToken = function( token, done ) {
var payload = jwt.decode(token);
if ( payload == null ){
return done( null, false );
}
console.log(payload);
var user = users[ payload.username ];
if ( user == null ||
user.id !== payload.id ||
user.username !== payload.username ) {
return done( null, false );
}
jwt.verify( token, user.secret, function ( error, decoded ) {
if ( error || decoded == null ) {
return done( error, false );
}
return done( null, user );
})
}
var bearerStrategy = new BearerStrategy( verifyToken )
Passport.use( 'bearer', bearerStrategy );
app.get(
'/userinfo',
Passport.authenticate( 'bearer', { session: false } ),
function ( req, res ) {
var user = request.user;
res.send( {
id: user.id,
username: user.username
});
}
);
app.listen( 3000, function() {
console.log( 'Listening on 3000' );
});
这是我从代码F.Y.I.中得到的一个代币
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ6YWNrIiwiaWF0IjoxNDU5MDAzMTYxfQ.rhqOX0ICRvivNCwwLNsu5KizNPLQTKPVEqfCuxtII90~
如果您正在使用这个,
var decoded = jwt.decode(token, {complete: true});
or
var payload = jwt.decode(token);
检查令牌是否与此类似->Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ6YWNrIiwiaWF0IjoxNDU5MDAzMTYxfQ.rhqOX0ICRvivNCwwLNsu5KizNPLQTKPVEqfCuxtII90~
然后,在将令牌令牌传递给jwt.decode之前,我们必须从令牌中删除Bearer,然后再传递它。Bearer是一种授权类型,需要删除。例如:
var newToken = token.substring(7, bearerString.length); // used to remove the Bearer string and space from the token so that it consists of only header,payload and signature.
var decoded = jwt.decode(newToken, { complete: true });
or
var payload = jwt.decode(newToken);
我认为问题是,当使用jwt.decode同时还具有密钥时,您需要将一个选项传递给decode调用,并将其完全设置为true:
来自jwt文档:
// get the decoded payload ignoring signature, no secretOrPrivateKey needed
var decoded = jwt.decode(token);
// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload)
https://github.com/auth0/node-jsonwebtoken
显然,最好在这里使用jwt.verify:
Warning: This will not verify whether the signature is valid. You should
not use this for untrusted messages. You most likely want to use jwt.verify instead.
我也遇到了这个问题,最终我需要在令牌周围抛出JSON.parse()。。。
var decoded = jwt.decode(JSON.parse(token))
相关文章:
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- 相同的RegExp返回不同的结果-第一次是正确的结果,第二次是null
- php函数的ajax html$_POST值返回null
- 谷歌地图API-“;toGeoJson”;返回几何体为null的对象
- 是否可以 document.getElementsByTagName('head')[0] ever 返回 null
- Firebase:查询返回null
- 在浅层渲染的反应组件上,Enzyme为道具返回null
- javascript对象显示为null,但object.properties返回数据
- PHP's json_decode返回空字符串(不是NULL)
- jQuery Multiselect插件返回null长度(应为0?)
- 如何处理getElementById返回Null
- JavaScript中的RegExp返回null
- node.js mongojs findOne回调返回错误为null
- Javascript 中的 RegEx 返回 Null
- 加载时的getelementbyID返回null
- 谷歌脚本在第二次调用Gmail后返回null
- Indexeddb OpenCursor在特定键值上返回null
- Ajax响应返回null
- null 返回 by JavaScript 中的 getElementById 方法
- 与typeof运算符一起使用时,javascript null返回对象