Errol Fitzgerald
Errol Fitzgerald

Reputation: 3008

Express+node CSRF Forbidden

I have seen similar problems, but none of the solutions have worked for me. I am using express 3, with ejs for templating. The token is being populated in the html like so:

<input type="hidden" name="_csrf" value="IS+SwCqr3j+vGW9QSqIk56ZC/">

This is what my template html looks like for the input field:

<input type="hidden" name="_csrf" value=<%= token %>/>

But when I submit the form I get

Error: Forbidden at Object.exports.error 

Here is what my main app configure function looks like

app.configure(function () {
    app.engine('.html', require('ejs').__express);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.static(__dirname + '/public'));
    app.use(express.session({
        store:  new mongoStore({
            url:'mongodb://localhost/test',
            maxAge: 300000
        }),
        secret: '076ee61d63ba104r4e34872411e433b2',
        cookie: {
            path     : '/',
            httpOnly : true,
            maxAge   : 1000*60*60*24*30*12
        }
    }));
    app.use(express.csrf());
    app.use(function(req, res, next){
        res.locals.token = req.session._csrf;
        next();
    });
    app.use(app.router);
});

The sessions are working fine, and the token is being populated so I am stuck on what to do now.

Upvotes: 2

Views: 2660

Answers (1)

Errol Fitzgerald
Errol Fitzgerald

Reputation: 3008

If anyone comes across this, I forgot to add quotes around the token

<input type="hidden" name="_csrf" value="<%= token %>"/>

Upvotes: 10

Related Questions