使用Node.js,我可以创建一个用户通过jwt.sign()分配一个令牌。这似乎有效。错误是当我尝试验证用户是否已登录时。我尝试验证标头是否存在,但req.headers.authorization给了我undefined。
//登录,这似乎工作正常。
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')
}
});
})
};
// authenticate,这是我无法验证标题
的地方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');
}
};
答案 0 :(得分:0)
使用req.headers['authorization']
或req.header('authorization')
您还必须检查authorization
标头是否在您的Nodejs认证服务器的Access-Control-Allow-Headers
中公开,以便客户端能够发送它。
示例代码
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization, Content-Type, Accept");
next();
});
https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
答案 1 :(得分:0)
使用jwt.verify(req.headers['authorization'], process.env.SECRET_KEY);
进行管理,您将获得令牌
答案 2 :(得分:0)
使用此
req.header("Access-Control-Allow-Origin", "*");
req.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization, Content-Type, Accept");
var token = req.body.token || req.query.token || req.headers['x-access-token'] || req.headers['Authorization'] || req.headers['authorization'];