使用express.js和locomotive.js在中间件中添加api令牌

lum*_*ked 2 node.js express locomotivejs

我正在构建一个我将使用angularjs前端的rest api服务器.我正在尝试实现一些在每个请求上运行的中间件.对于每个请求我想要检查api令牌(如果存在)继续检查是否有效,如果不存在则返回未经授权的响应而不完成请求.

在我尝试添加中间件之前请求工作,但是一旦我尝试添加中间件或在主路由超时之前捕获路由.

http://localhost:3000/developer/test?api=fhgjtyd6fjrj4off6r4rhgjdldksrghiue750f
{
    response: {
        id: "test",
        api: "fhgjtyd6fjrj4off6r4rhgjdldksrghiue750f"
    }
}
Run Code Online (Sandbox Code Playgroud)

这两条路线都可以使用,但我更喜欢资源版本.(http://locomotivejs.org/guide/routing/)

this.match('/developer', { controller: 'developer', action: 'show' });

this.resources('developer');
Run Code Online (Sandbox Code Playgroud)

这是我一直试图遵循的一个例子,因为它看起来像我需要做的.(http://webapplog.com/intro-to-express-js-parameters-error-handling-and-other-middleware/),但目前我试图实现这样的方式,它超出了路线.它将在方法中使用console.log(),但它就像是等待它永远不会得到的东西.如果我尝试使用next()我得到一个未定义的错误,我不想将应用程序注入Authenticator或任何其他对象.

function requiredParamHandler(param){
    //do something with a param, e.g., check that it's present in a query string
    return function (req,res, next) {
    //use param, e.g., if token is valid proceed with next();
        next();
    });
 }

 app.get('/api/v1/stories/:id', requiredParamHandler('token'), story.show);

     var story  = {
         show: function (req, res, next) {
             //do some logic, e.g., restrict fields to output
             return res.send();
         }
      } 
Run Code Online (Sandbox Code Playgroud)

我开始构建一个Auth模块,该模块将使用其中的方法来检查和验证api令牌.

var Authenticator = function () {

    this.requireApiToken = function() {
        console.log('requireApiToken');

    }

};

module.exports = Authenticator;  
Run Code Online (Sandbox Code Playgroud)

我试着按照他们的api参考文档中的表达方式去做

app.all(path, [callback...], callback)

app.all('/api/*', requireAuthentication);
Run Code Online (Sandbox Code Playgroud)

我在机车config/environments/all.js里面添加了这一行

auth = new Authenticator();
this.express.all('*', auth.requireApiToken);
Run Code Online (Sandbox Code Playgroud)

但这是路线开始超时的时候,我甚至没有得到错误或任何东西;

我也试过使用常规路由方法,但它做了同样的事情.

this.match('/developer/:id', auth.requireApiToken, { controller: 'developer', action: 'show' });
Run Code Online (Sandbox Code Playgroud)

我想捕获所有到达服务器的路由,并检查查询字符串中是否存在api令牌.如果不存在则返回未经授权的响应,如果存在则进行检查,如果所有商品继续路由到正确的路由/控制器.你是如何利用机车实现这一目标并防止路线超时的?

rob*_*lep 5

你requireApiToken应该充当一个适当的中间件,这不是(它只是console.log一些东西).

使用中间件,您需要发回响应,或使用以下next函数继续运行中间件链:

var Authenticator = function () {

  this.requireApiToken = function(req, res, next) {
    console.log('requireApiToken');
    next();
  };

};

module.exports = Authenticator;
Run Code Online (Sandbox Code Playgroud)

此外,机车从Express复制一些功能,因此您可以直接使用它们,而不必使用它们this.express来使它们工作.所以这也应该工作(in config/environment/*.js):

var auth = new Authenticator;
this.use(auth.requestApiToken);
Run Code Online (Sandbox Code Playgroud)