【问题标题】:public/private rest API公共/私人休息 API
【发布时间】:2012-08-03 12:49:33
【问题描述】:

我正在使用 Express.js 框架在 Node.js 中构建 REST JSON Api。对于身份验证,我使用 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 中正确分离公共和私有功能?我希望我的问题很清楚。

感谢您的帮助。

【问题讨论】:

  • @helmus ...随便叫什么,我叫功能,我的自行车有功能,我的api也有,什么没用的评论。
  • 抱歉并不是粗鲁,只是想保持清楚,请查看此线程以获取更多信息stackoverflow.com/questions/7551/…
  • @onlineracoon 你所说的公共/私人是什么意思?你到底想分开什么?
  • @freakish 我的意思是,当用户登录时,他们可以访问 API 的“私有”功能,当用户未登录时,他们只能做某些事情(登录、注册、恢复密码等)。 )

标签: javascript node.js express


【解决方案1】:

不要使用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!" );
});

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2014-07-14
    • 2017-02-17
    • 2011-01-09
    • 2013-01-31
    相关资源
    最近更新 更多