从另一个中间件调用中间件

从另一个中间件调用中间件

本文介绍了Express:从另一个中间件调用中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Express 4 的新手,我想知道如何实现此功能:我正在使用jwt来验证我的API的使用者,为此我做了一个一个简单的中间件来检查jwt令牌的有效性:

I'm new to Express 4 and i'm wondering something about how to implement this thing: I'm using jwt to authenticate the consumer of my API, to do that i have a pretty simple middleware to check the validity of the jwt token:

var requireValidToken = function(req, res, next) {
  var token = req.body.token || req.query.token || req.headers['x-access-token'];
  if (token) {
    try {
      var decoded = jwt.verify(token, req.app.get('superSecret'));
    } catch(err) {
      return res.json({ success: false, message: 'Failed to authenticate token.' });
    }
    req.user = decoded.user;
    next();
  } else {
    return res.status(403).send({
        success: false,
        message: 'No token provided.'
    });
  }
};

这工作得很好,但是现在,我想扩展它以便能够检查用户的角色:

This is working pretty well, but now, i want to extend this to be able to check the role of the user:

 router.get('/anAdminRoute', requireRole('ROLE_ADMIN'), function (req, res, next) {
      // some code...
 });

所以我为此添加了一个中间件:

So i added a middleware for this:

var requireRole = function(role) {
  return function(req, res, next){
    // Dummy tests...
    if(req.user.role == roles.admin || req.user.role == role){
      next();
    } else {
      return res.status(403)({
        success: false,
        message: "Token valid, but you don't have the right permission to access this resource :)"
      });
    }
  }
}

但是由于这个requireRole()函数显然检查了有效的jwt令牌,所以我想知道如何在此函数内调用我的requireValidToken中间件,因此不必为要保护的每条路由都显式调用它.

But as this requireRole() function while obviously checks for a valid jwt token, i'm wondering how can i call my requireValidToken middleware within this function, and so not having to explicitly call it for each route i want to protect.

一个简单的解决方案是不使用 requireValidToken 作为中间件,但我仍然希望能够使用它来保护某些路由

An easy solution would have been not to use requireValidToken as a middleware but i still want to be able to use it to protect certain routes

解决方案

束缚中间件很简单:

var middleware2 = function(param) {
  return function(req, res, next){
    middleware1(req, res, function(){
      // middleware2 code
    });
  }
}

如果有人感兴趣,那是我验证用户角色的最终可行解决方案:

If anybody interested, my final working solution to validate a user role:

var jwt = require('jsonwebtoken'),
  roles = require('../models/user').roles;

// authentication middleware
// check if the given jwt token is valid
var requireValidToken = function(req, res, next) {
  var token = req.body.token || req.query.token || req.headers['x-access-token'];
  if (token) {
    try {
      var decoded = jwt.verify(token, req.app.get('superSecret'));
    } catch(err) {
      return res.json({ success: false, message: 'Failed to authenticate token.' });
    }
    req.user = decoded.user;
    next();
  } else {
    return res.status(403).send({
        success: false,
        message: 'No token provided.'
    });
  }
};

var requireRole = function(role) {
  return function(req, res, next){
    requireValidToken(req, res, function(){
      if(req.user.role == roles.admin || req.user.role == role){
        next();
      } else {
        return res.status(403).send({
          success: false,
          message: "Token valid, but you don't have the right permission to access this resource :)"
        });
      }
    });
  }
}

module.exports = {
  requireValidToken: requireValidToken,
  requireRole: requireRole
}

推荐答案

完全误读了您的问题.如果要在某些情况下调用 requireValidToken ,则可以将req和res对象以及匿名回调传递给中间件函数.如何获得中间件功能很大程度上取决于您的应用程序体系结构,因此我假设我在上下文中具有 requireValidToken :

Completely misread your question. If you want to call requireValidToken for certain situations, you can pass along the req and res objects to the middleware function, along with an anonymous callback. How you get the middleware function largely depends on your application architecture so I'll assume I have the requireValidToken within my context:

var requireRole = function(role) {
  return function(req, res, next){
    // Dummy tests...

    requireValidToken(req, res, function () {
      if(req.user.role == roles.admin || req.user.role == role){
        next();
      } else {
        return res.status(403)({
          success: false,
          message: "Token valid, but you don't have the right permission to access this resource :)"
        });
      }
    });
  }
};

这篇关于Express:从另一个中间件调用中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:13