Node.js use csurf conditionally with express 4

时光毁灭记忆、已成空白 提交于 2019-12-03 14:11:06
Ben Fortune

According to this you need to split it up into two routers, one using csurf and one not. You'd then apply the middleware to the router instead of the app.

var routes = express.Router();
var csrfExcludedRoutes = express.Router();

routes.use(csrf());

routes.get('/', function(req, res) {
    //has req.csrfToken()
});

csrfExcludedRoutes.get('/myApi', function(req, res) {
    //doesn't have req.csrfToken()
});

This is an old thread but I stumbled across it and thought I'd try to address the question that @marshro brings up about the oddity of calling csrf()(req, res, next) in the middleware.

What's happening here is that csurf returns a function from the require statement that is itself used to build a middleware function with some optional configuration parameters.

The call to csrf() used in your middleware above builds the middleware function with default options for EVERY incoming request that needs csrf protection. If you really want to use this approach you DO have an opportunity to make a simple change to make your solution more efficient a very small restructuring to build the middleware once:

// 1. Build the csrf middleware function 'csrfMw' once.
var csrfMw = csrf();          

app.use(function(req, res, next){
    if (csrfExclusion.indexOf(req.path) !== -1) {
        next();
    } else {
        // 2. Use the middleware function across all requests.
        csrfMw(req, res, next);  
    }
);

This said - when you have the opportunity you might want to check out the docs again - there are two methods recommended for avoiding this approach. The first sets up middleware csrfProtection and applies it to select routes. The second sets up two routers as @ben-fortune mentioned above - one that applies csrf to everything and one that does not. Both would be more efficient than having an exclusions condition.

All this said - I can see the case to have an exclusions list and may use your approach if I don't have the time to split apart routes manually. ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!