0
나는 nodejs와 postgreSQL을 사용하여 안드로이드 응용 프로그램을 개발 중입니다. 지금은 로그인과 등록 만하고 있습니다.요청할 때마다 Jwt 토큰을 확인 하시겠습니까?
내가 로그인 할 때 서버가 나에게 토큰을 보내면 토큰이 SharedPreference 장치에 저장됩니다. 이제는 혼란 스럽습니다. 모든 요청에 대해이 토큰을 디코딩해야합니까, 아니면해야합니까? 한 번만 해?
this tutorial 마지막에, 그는 모든 경로에서 토큰을 디코딩합니다. 그러나 예를 들어 등록 요청을 할 때 토큰을 디코딩하지 않아도됩니다.
이것을 구현하는 가장 좋은 방법은 무엇입니까? 당신은 모든 경로에 대한 JWT 토큰 체크를 사용하지 않을 경우
//****************************************************Begin of login request **********************************/
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
});
});
//****************************************************End of Login request **********************************/
//****************************************************Begin of register request******************************/
router.post('/register', function (req, res, next) {
if (JSON.stringify(req.body) == "{}") {
return res.status(400).json({ Error: "Register request body is empty" });
}
if (!req.body.email || !req.body.username || !req.body.password) {
return res.status(400).json({ Error: "Missing fields for registration" });
}
var password = User.generateHash(req.body.password);
User.create({
username: req.body.username,
email: req.body.email,
password: password
}).then(function() {
return res.status(200).json({ message: "user created" });
}).catch(function (err) {
return res.status(400).send({ message: err.message }); //
}).catch(function (err) {
return res.status(400).json({ message: "issues trying to connect to database" });
})
});
//****************************************************End of register request **********************************/
module.exports = router;