简体   繁体   中英

Nodejs restful api auth method

How to properly do auth in nodejs restful API? I've created basic API, for example example.com/books/ will give ua 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?

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, ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM