如何验证标头是否存在?

3
使用Node.js,我能够通过jwt.sign()创建一个用户并分配一个token。这似乎是有效的。但是当我尝试验证用户是否已登录时出现错误。我尝试验证头部是否存在,但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')
                }
    });
  })

};

//进行身份验证,这是我无法验证标题的位置

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”头的部分吗?顺便说一句,这是你必须在代码中完成的事情,浏览器不会自动处理。 - robertklep
3个回答

3

请使用req.headers['authorization']req.header('authorization')

您还必须检查Access-Control-Allow-Headers中是否公开了authorization标头,以便您的客户端能够发送它到Nodejs身份验证服务器。

示例代码

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


req.headers['authorization']req.headers.authorization 是相同的。 - robertklep
1
没错,你也可以使用 req.header('authorization') - Stephane Janicaud
但这正是问题所在:req.headers.authorization并不存在。 - robertklep
然后它不能被认证服务器暴露。 - Stephane Janicaud
你说得完全正确,我读他的代码太快了。另一个可能性是 authorization 标头没有被允许在 Access-Control-Allow-Headers 列表中。 - Stephane Janicaud
显示剩余3条评论

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'];

-1

使用jwt.verify(req.headers['authorization'], process.env.SECRET_KEY);,控制台会返回你的token。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接