onl*_*oon 1 javascript node.js express
我正在使用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){
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能在REST api中正确分离公共和私有函数?我希望我的问题很明确.
感谢帮助.
不要使用,app.use因为它将中间件添加到所有路由.像这样定义您的身份验证处理程
function authentication_required(req, res, next){
// The other authentication code goes here.
};
Run Code Online (Sandbox Code Playgroud)
现在你可以在每条路线上做(例如)这个:
// 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!" );
});
Run Code Online (Sandbox Code Playgroud)