【发布时间】:2017-09-05 15:35:53
【问题描述】:
使用 Node.js,我可以创建一个用户并通过 jwt.sign() 分配一个令牌。这似乎奏效了。错误是当我尝试验证用户是否已登录时。我尝试验证标头是否存在,但 req.headers.authorization 给我未定义。
//登录,这似乎工作正常。
module.exports.login = function(req, res) {
console.log('logging in a Auth_user')
console.log(req.body)
models.Auth_user.findOne({
where: {email: req.body.email}
}).then(function(user) {
// console.log(user)
console.log(user.email)
console.log(user.first_name)
console.log(user.password)
if (user == null){
console.log('no user found with email')
// res.redirect('/users/sign-in')
}
bcrypt.compare(req.body.password, user.password, function(err, result) {
if (result == true){
console.log('password is valid')
var token = jwt.sign({ username: user.email }, 'passwordgoeshere', { expiresIn: 600 });
return res.send()
res.status(200).json({success: true, token: token});
res.redirect('/holders')
}
else{
console.log('password incorrect')
res.redirect('/home')
}
});
})
};
//认证,这是我无法验证标头的地方
module.exports.authenticate = function(req, res, next) {
console.log('authenticating')
console.log(req.headers.authorization)
var headerExists = req.headers.authorization;
if (headerExists) {
var token = req.headers.authorization.split(' ')[1]; //--> Authorization Bearer xxx
jwt.verify(token, 'passwordgoeshere', function(error, decoded) {
if (error) {
console.log(error);
res.status(401).json('Unauthorized');
} else {
req.user = decoded.username;
var authenticated = true;
next();
}
});
} else {
res.status(403).json('No token provided');
}
};
【问题讨论】:
-
您能否显示将
Authorization标头发送到服务器的客户端代码? FWIW,这是您必须在代码中执行的操作,而不是浏览器会自动执行的操作。
标签: node.js authentication token jwt