【问题标题】:Add api token in middleware using express.js and locomotive.js使用 express.js 和 locomotive.js 在中间件中添加 api 令牌
【发布时间】:2013-11-06 04:14:26
【问题描述】:

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

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

http://localhost:3000/developer/test?api=fhgjtyd6fjrj4off6r4rhgjdldksrghiue750f
{
    response: {
        id: "test",
        api: "fhgjtyd6fjrj4off6r4rhgjdldksrghiue750f"
    }
}

这两种方法都可以,但我更喜欢资源版本。 (http://locomotivejs.org/guide/routing/)

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

this.resources('developer');

这是一个我一直在尝试遵循的示例,因为它看起来主要是我需要做的。 (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();
         }
      } 

我开始构建一个 Auth 模块,其中包含检查和验证 api 令牌的方法。

var Authenticator = function () {

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

    }

};

module.exports = Authenticator;  

我尝试按照他们在 api 参考文档中所说的做

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

app.all('/api/*', requireAuthentication);

我在 locomotives config/environments/all.js 中添加了上面那一行

auth = new Authenticator();
this.express.all('*', auth.requireApiToken);

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

我也尝试过使用常规路由方法,但效果相同。

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

我想捕获所有到达服务器的路由并检查查询字符串中是否存在 api 令牌。如果不存在,则发回未经授权的响应,如果存在则进行检查,如果一切正常,则继续路由到正确的路由/控制器。您如何使用机车完成此任务并防止路线超时?

【问题讨论】:

    标签: node.js express locomotivejs


    【解决方案1】:

    您的 requireApiToken 应该充当适当的中间件,但事实并非如此(它只是 console.log 的东西)。

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

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

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

    var auth = new Authenticator;
    this.use(auth.requestApiToken);
    

    【讨论】:

    • 谢谢。我没有意识到 express 会为你注入 req, res, next 。我很新快递和机车,2天新。
    猜你喜欢
    • 2019-05-01
    • 2020-10-04
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    相关资源
    最近更新 更多