public/private rest API

I'm building a REST JSON Api in Node.js with the Express.js framework. For authentication I use HTTP basic. This is my code so far:

var express = require('express');
var app = express();

app.configure(function(){
  app.use(express.bodyParser());
});

// Http basic auth.

app.use(function(req, res, next){
  if(req.headers.authorization && req.headers.authorization.search('Basic ') === 0){
    var header = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString();
    var headerSplit = header.split(':');
    var username = headerSplit[0];
    var password = headerSplit[1];

    if(username && password && (username.length >= 4 && password.length >= 2){
        if(auth(username, password)){
          next(); return;
        } else {
          res.send('Authentication required', 401);
        }
    }
  } else {
    res.header('WWW-Authenticate', 'Basic realm="Login with username/password"');
    res.send('Authentication required', 401);
  }
});

// Public
app.post('/restore-password', function(req, res){
});

// Public
app.get('/search', function(req, res){
});

// Public
app.post('/users', function(req, res){
});

// Private
app.get('/user', function(req, res){
});

// Private
app.get('/protected-data', function(req, res){
});

How could I properly seperate public and private functions in my REST api? I hope my question is clear.

Thanks for help.


Don't use app.use because it adds the middleware to all routes. Define your authentication handler like this:

function authentication_required(req, res, next){
    // The other authentication code goes here.
};

And now in every route you can do (for example) this:

// Public
app.post("/restore-password", function(req, res) {
    console.log( "No need for authentication!" );
});

// Private (add authentication_required middleware to the route)
app.get("/settings", authentication_required, function(req, res) {
    console.log( "I'm authenticated, so I can read this!" );
});
链接地址: http://www.djcxy.com/p/71358.html

上一篇: 任何Spring Framework对REST安全性的支持?

下一篇: 公共/私人休息API