【发布时间】:2017-10-14 17:05:19
【问题描述】:
我正在使用 android、nodeJS 和 postgreSQL(sequelize) 构建客户端-服务器应用程序,我已经能够进行简单的登录和注册,但我想保存会话,所以我这样做了:
router.post('/login', function (req, res, next) {
if (JSON.stringify(req.body) == "{}") {
return res.status(400).json({ Error: "Login request body is empty" });
}
if (!req.body.username || !req.body.password) {
return res.status(400).json({ Error: "Missing fields for login" });
}
// search a user to login
User.findOne({ where: { username: req.body.username } }) // searching a user with the same username and password sended in req.body
.then(function (user) {
if (user && user.validPassword(req.body.password)) {
//return res.status(200).json({ message: "loged in!" }); // username and password match
var payload = { user: user };
// create a token
var token = jwt.sign(payload, 'superSecret', {
expiresIn: 60 * 60 * 24
});
// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
else {
return res.status(401).json({ message: "Unauthorized" }); // if there is no user with specific fields send
}
}).catch(function (err) {
console.error(err.stack)
return res.status(500).json({ message: "server issues when trying to login!" }); // server problems
});
});
正如你们所看到的,当登录成功时,我将令牌返回给客户端,在客户端,我将令牌保存在 SharedPreferences 上。
我的问题是token有过期时间,那么如何控制token的过期时间,应该在服务器端控制,还是在客户端控制呢?
任何提示都是有用的。 谢谢
【问题讨论】:
标签: java android json node.js jwt