【问题标题】:CSRF protection for Node.js Express 4 and passport.js not workingNode.js Express 4 和 passport.js 的 CSRF 保护不起作用
【发布时间】:2019-06-27 15:01:56
【问题描述】:

使用 csurf,我正在尝试将 csrf 保护集成到我的 node.js express 4 应用程序中。这是我的代码:

编辑:下面的代码是根据我找到的解决方案更新的。

    "use strict";
    var http = require('http');
    var https = require('https');

    var port = process.env.PORT || 80,
     express = require('express'),
     csrf = require('csurf'),
     bodyParser = require('body-parser');

    var LocalStrategy = require('passport-local').Strategy,
        csrfProtection = csrf({ cookie: true }),
        mongoose = require('mongoose'),
        conn = mongoose.createConnection('foo'),
        cookieParser = require('cookie-parser'),
        passport = require('passport'),
            session = require('express-session'),
            MongoStore = require('connect-mongo')(session),
            app = express();

        app.set('view engine', 'ejs');
        var csrfProtection = csrf({ cookie: true }); // doesn't work either
        require('passport')(passport); 
        app.use(cookieParser("foo")); 
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({extended: true})); //extended: true|false does not make any difference

        app.use(session({
            //foo
        }));

        app.use(passport.initialize());
        app.use(passport.session()); 

        require('./app/routes.js')(app, passport); //routes inside here cause a ReferenceError: csrfProtection is not defined  

        http.createServer(app).listen(port);
        https.createServer(options, app).listen(443, function () {
            //foo
        });

-- routes.js --

        var csrf = require('csurf'), //this needs to go in here
            csrfProtection = csrf(); //this needs to go in here

    module.exports = function(app, passport) {
       app.route('/somepage')
       .get(csrfProtection, function(req, res) { 
          res.render('somepage', { csrfToken: req.csrfToken()});
       });
    };

-- routes.js end--

由于某些奇怪的原因,csrfProtection 在我的页面路由中仍然未知,导致 ReferenceError(请参阅代码中的注释)。我错过了什么?

【问题讨论】:

    标签: node.js passport.js csrf express-4


    【解决方案1】:

    编辑: 忽略方法 将禁用 CSRF 令牌检查的方法数组。默认为 ['GET', 'HEAD', 'OPTIONS']。
    尝试将其设置为['HEAD','OPTIONS']

    csrfProtection = csrf(
        { cookie: true, ignoreMethods:['HEAD','OPTIONS' ] }
    )
    

    【讨论】:

    • 我根据你的想法更改了我的代码,但它仍然给我相同的页面路由参考错误。
    • 此外,我不想将它用于所有页面路由,而仅用于特定的。因此: app.use() 不是要走的路。
    • 我更新了答案,你有没有机会让它工作?
    • 我搞定了。我错过了受影响的路线存储在单独的文件中的事实。我更新了我的代码以可视化这一点并显示问题是如何解决的。无论如何,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 2013-09-17
    • 2019-12-31
    • 2014-07-01
    • 1970-01-01
    • 2015-11-01
    • 2019-02-03
    • 2019-11-29
    相关资源
    最近更新 更多