我正在使用Express.js框架在Node.js中构建REST JSON Api。对于身份验证,我使用HTTP basic。到目前为止,这是我的代码:
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中正确分离公共和私有函数?我希望我的问题很明确。
感谢您的帮助。
答案 0 :(得分:6)
请勿使用app.use
,因为它会将中间件添加到所有路由中。像这样定义您的身份验证处理程序:
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!" );
});