保护csrf Nodejs表单

时间:2018-05-24 07:32:20

标签: node.js methods csrf

我的Nodejs应用程序有点问题。我想用csrf令牌保护我的表单,但它不起作用。我有一个像

这样的错误
ForbiddenError: invalid csrf token
POST http://localhost:3000/addfile 403 (Forbidden)

我想为所有请求创建csrf令牌。我可以创建csrf令牌,但如果我使用像:POST / PUT或DELETE这样的方法,它就不起作用了。

我不明白为什么会出现这个错误。谢谢你的回答。

app.js

var express             = require("express");
var bodyParser          = require("body-parser");
var mongoose            = require('mongoose');
var fs                  = require('fs');
var path                = require('path');
var logger              = require('morgan');
var expressValidator    = require('express-validator');
var csrf                = require('csurf');
var session             = require('express-session');
var passport            = require('passport');
var PORT                = 3000;
var config              = require('./config/database');
var app                 = express();

// Connexion to MongoDb
mongoose.connect(config.database, function(err) {
    if(err){
        console.log(err);
    }
    else{
        console.log("Connected to MongoDb");
    }
});
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(expressValidator());
app.set('views',path.join(__dirname, ''));
app.set('view engine','pug');
app.use(express.static(path.join(__dirname, '')));
app.disable('x-powered-by');
app.use(session({
    name: 'SESS_ID',
    secret: config.secret,
    resave: true,
    saveUninitialized: true,
    cookie: {
        secure: false,
        httpOnly: true,
        maxAge: 5*60*1000 } //15minutes*60sec*1000ms
    //cookie: {secure: false}   //https = true, http=false
}));
app.use(csrf());
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);

app.use(function(req, res, next)  {
    res.locals._csrf = req.csrfToken();
    next();
});

app.use('/', require('./routes/fileRoutes'));
app.use('/', require('./routes/authRoutes'));

app.listen(PORT,function(){
    console.log("Server started at the port " + PORT);
});

路由/ fileRoutes.js

app.get('/',function(req,res){
    File.find(function(err, files){
        res.render('views/layout',{files:files});
    });
});
app.post('/addfile',upload,function(req,res){
    if (req.fileValidationError) {
        return res.end("Error PDF");
    } else {
        for (var i = 0; i < req.files.length; i++)
        {
            var files = new File ();  
                files.fieldname= req.files[i].fieldname;
                files.originalname= req.files[i].originalname;
                files.encoding= req.files[i].encodin;
                files.path= req.files[i].path;
                files.save(function(err, data){
            });
        }
        res.redirect('/');
    }
});

layout.pug

form#uploadForm(enctype='multipart/form-data', action='/addfile', method='post')
    input(type='hidden', name='_csrf', value=_csrf)
    input(type='file', name='userPhoto', multiple='')
    input(type='submit', value='Upload Image', name='submit')
    input#random(type='text', name='random')

1 个答案:

答案 0 :(得分:0)

我看到你有:

.kv

如果你控制台.log(_csrf)的价值是多少?我也注意到你没有把它放在引号中。