1

How to properly do auth in nodejs restful API? I've created basic API, for example example.com/books/ will give u a list of books from my db. I can allow the logged in user to use the API, through the checking of the session is there or not. Is it that simple? Why need a token based auth?

  • if you are using `expressjs` then there is a good tutorial here on the same - http://code.runnable.com/UTlPPF-f2W1TAAEY/login-auth-using-sessions-in-express-for-node-js-and-authentication – Chandan Nov 25 '15 at 05:25
  • @Chandan do u know why I need to use token instead of session? – Jennifer Aniston Nov 25 '15 at 09:14
  • You said RESTful APIs thats why... it is not a good practise to use sessions with Restful APIs. Check here - http://stackoverflow.com/questions/671118/what-exactly-is-restful-programming – Chandan Nov 25 '15 at 09:30

1 Answers1

0

It depends on what kind of security you want to implement. Every You could leverage HTTP basic auth. This simply corresponds to have a Authorization header that contains the username / password encoded with Base64:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

For information QWxhZGRpbjpvcGVuIHNlc2FtZQ== equals to encodeBase64('username:password) (pseudo code).

On the server side and within an Express application, you could use the basic-auth module to implement the following security middleware. It will extract the username / password from the request and check if it matches. It's hard coded here for simplicity but it should check the database.

var basicAuth = require('basic-auth');

function unauthorized(res) {
  res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
  return res.status(401).end();
}

// Hardcoded username / password
var username = 'foo';
var password = 'bar';

var basicAuthMiddleware = function() {
  return function(req, res, next) {
    var user = basicAuth(req);

    if (!user || !user.name || !user.pass) {
      return unauthorized(res);
    }

    if (user.name === username && user.pass === password) {
      return next();
    } else {
      return unauthorized(res);
    }
  };
};

expressApplication.use(basicAuthMiddleware);

If you want something more generic, i.e. the ability to change easily the authentication strategy, I would recommend you to have a look at the Passport library.

In this case, the previous would be reworked as described below:

var passport = require('passport');

passport.use(new BasicStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) {
        return done(err);
      }

      if (!user) {
        return done(null, false);
      }

      if (!user.validPassword(password)) {
        return done(null, false);
      }

      return done(null, user);
    });
  }
));

expressApplication.use(passport.initialize());

You could also use more advanced security mechanisms like token-based authentication or OAuth2. Passport provides some supports for them.

Otherwise I would recommend you to read the following blog post:

One remark. When you implement a RESTful service, you shouldn't have some state on the server side. I mean there is no login and logout. If you want to leverage token, you should need to an authorization resource that gives you a temporary token for credentials with the ability to refresh it when it expired.

Hope it helps you, Thierry

Thierry Templier
  • 182,931
  • 35
  • 372
  • 339