Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to verify header exist?

Using Node.js, I am able to create a user an assign a token via jwt.sign(). This seems to be working. The error is when I try to validate that the user is logged in. I try to verify that the header exist but req.headers.authorization gives me undefined.

//login, this seems to work fine.

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, this is where I cannot verify header

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');
  }
};
like image 369
Edwin Rodriguez Avatar asked Sep 14 '26 15:09

Edwin Rodriguez


1 Answers

Use either req.headers['authorization'] or req.header('authorization')

You must also check that authorization header is exposed in Access-Control-Allow-Headers of your Nodejs authentication server in order your client is able to send it.

Sample code

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

like image 177
Stephane Janicaud Avatar answered Sep 16 '26 06:09

Stephane Janicaud