公共/私人restAPI

我使用Express.js框架在Node.js中构build了一个REST JSON Api。 对于身份validation,我使用HTTP基本。 这是我的代码到目前为止:

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){ }); 

我怎么能在我的REST API中正确分离公共和私有的function? 我希望我的问题很清楚。

感谢帮助。

不要使用app.use因为它将中间件添加到所有路由。 像这样定义你的authentication处理程序:

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

现在你可以在每条路线上做(例如):

 // 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!" ); });