无法使用csurf验证我的csrf-token(Node.js)

时间:2017-12-14 18:33:13

标签: node.js csrf-protection

我无法在这个基本的测试应用程序中使用csurf,无论我做什么我总是得到" ForbiddenError:无效的csrf令牌"发送表格后。

我做错了什么?我试图按照in the documentation for csurf给出的示例(虽然我也使用TLS - 可能会影响结果吗?)。

'use strict'

var https = require('https');
var express = require('express');
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var fs = require('fs');
var oauth = require('./oauth.js');
var argv = require('minimist')(process.argv.slice(2), {
    alias: {p: 'port'},
    default: {port: 80},
});

// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })

var app = express();

app.use(cookieParser());

// Init SSL
var sslPath = '/etc/letsencrypt/live/censored/';
var options = {
    key: fs.readFileSync(sslPath + 'privkey.pem'),
    cert: fs.readFileSync(sslPath + 'fullchain.pem')
};

app.get('/some-form', csrfProtection, function(req, res){
        res.send('<form action="/process" method="POST">' +
                    '<input type="hidden" name="_csrf" value="' + req.csrfToken() + '">' +
                    'Favorite color: <input type="text" name="favoriteColor">' +
                    '<button type="submit">Submit</button>' +
                    '</form>');
});

app.post('/process', csrfProtection, function(req, res){
        res.send('<p>Your favorite color is "' + req.body.favoriteColor + '".');
});


app.get("/", function(req, res) {
    res.send('Hello World!');
});
app.listen(argv.port, function() {
    console.log('listening on port ' + argv.port);
});

https.createServer(options, app).listen(443);

1 个答案:

答案 0 :(得分:0)

我忘记使用parseForm,一旦我这样做,一切正常!