We help IT Professionals succeed at work.

How to Authenticate Remote User on Node.js Server?

Michael Vasilevsky
Michael Vasilevsky used Ask the Experts™
on
I have a node.js app and am developing a separate single page app (that will eventually be converted into Android and iOS native apps). I'm setting up an API on the node.js app and am struggling with authentication. The node.js app is using passport-local for authentication and I store user data in a MongoDB backend.

So far, I have a GET and POST routes that look like this:
router.get('/api/devices', catchErrors(deviceController.getDevicesAPI));
router.post('/api/devices', authController.isAuthorized, catchErrors(deviceController.getDevicesAPI));

Open in new window


My remote authentication request looks like this:
const axios = require('axios');
const url = 'http://localhost:7777/api/devices';
const user = {
  username,
  password,
};

function authenticate() {
  axios
    .post(url, user)
    .then(function(response) {
      console.log('Authenticated ', response);
    })
    .catch(function(error) {
      console.log('Error on Authentication ', error);
    });
}

Open in new window


My question is how can I take the username/password in the HTTP request to authenticate against an existing user in the node.js app? I was hoping I could just pass the values to passport-local, something like :

exports.isAuthorized = (req, res, next) => {
  const username = req.body.username;
  const password = req.body.password;
  passport.authenticate('local', function(err, user, info) {
    
    console.log(req.body);
    if (err) { return next(err); }
    next();
  })(req, res, next);
};

Open in new window


but this does nothing. With research, it seems I may need to use JSON Web Tokens. Is that the path I should go down? Any other recommended approach?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Solutions Architect
Commented:
This is the way I did it:

exports.isAuthorized =  async (req, res, next) => {
  const username = req.body.username;
  const password = req.body.password;
  const user = await User.findOne({ email: username });
  let token = req.header['auth-token'];

  if (!user) {
    res.sendStatus(403);
    return;
  }

  if (token) {
    jwt.verify(token, process.env.SECRET, function(err, response) {
      if (err) {
        res.sendStatus(403);
        return;
      } else {
        console.log('verified token');
        return next();
      }
    });
  }

  user.authenticate(password, function(err, result) {
    if (result) {
      token = jwt.sign({ _id: user._id}, process.env.SECRET);
      res.header('auth-token', token);
      return next();
    }
    res.sendStatus(403);
  });
};

Open in new window