admin管理员组文章数量:1278916
I just implemented jwt-simple,on my backend in nodejs.i want to expire token by given time.
var jwt = require('jwt-simple');
Schema.statics.encode = (data) => {
return JWT.encode(data, CONSTANT.ADMIN_TOKEN_SECRET, 'HS256');
};
Schema.statics.decode = (data) => {
return JWT.decode(data, CONSTANT.ADMIN_TOKEN_SECRET);
};
how to add expires time in jwt-simple
I just implemented jwt-simple,on my backend in nodejs.i want to expire token by given time.
var jwt = require('jwt-simple');
Schema.statics.encode = (data) => {
return JWT.encode(data, CONSTANT.ADMIN_TOKEN_SECRET, 'HS256');
};
Schema.statics.decode = (data) => {
return JWT.decode(data, CONSTANT.ADMIN_TOKEN_SECRET);
};
how to add expires time in jwt-simple
Share Improve this question asked Oct 19, 2016 at 7:00 codercoder 5381 gold badge5 silver badges18 bronze badges5 Answers
Reset to default 5There is no default exp
. Two ways you can add it mannually:
With plain js:
iat: Math.round(Date.now() / 1000), exp: Math.round(Date.now() / 1000 + 5 * 60 * 60)
With
moment.js
:iat: moment().unix(), exp: moment().add(5, 'hours').unix()
Source from original Github repository.
You can validate your token with a expirate date in the passport Strategy function, like this:
passport.use(new JwtStrategy(opts, function(jwt_payload, done){
User.find({id: jwt_payload.id}, function(err, user){
if (err) {
return done(err, false, {message: "Incorrect Token!!"});
}
if (user) {
if (user[0].token_expiration_date <= Date.now()){
return done(null, false, {message: "Expired Token"});
}else{
return done(null, user);
}
}else{
return done(null, false, {message: "Incorrect Token"});
}
});
}));
Hope that this can help you.
To be more precise, add exp
attribute in your data object where exp
is expiry time in unix format.
e.g.
var data = {"data":["some data"],exp:16872131302}
var jwt = require('jwt-simple');
Schema.statics.encode = (data) => {
return JWT.encode(data, CONSTANT.ADMIN_TOKEN_SECRET, 'HS256');
};
Schema.statics.decode = (data) => {
return JWT.decode(data, CONSTANT.ADMIN_TOKEN_SECRET);
};
Use jsonwebtoken instead.
https://github./auth0/node-jsonwebtoken
const jwt = require(`jsonwebtoken`)
const token = jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: '1h' });
You can use the exp field in the payload before calling the create function and for example you can use moment to get the time and add whatever you want. If you want to check if the token is expired or other type of error you can use jwt-simple-error-identify instead.
In his documentation there is an example of that.
https://www.npmjs./package/jwt-simple-error-identify
本文标签: javascriptHow to expire token in jwtsimpleStack Overflow
版权声明:本文标题:javascript - How to expire token in jwt-simple? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741277798a2369831.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论