Dan
Dan

Reputation: 57881

Any way of geting csrfToken in POST request in express?

In my app I have a code from official docs, except one difference: I send xsrfToken in response to POST request, not GET.

var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')

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

var app = express()

// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())

app.post('/getCsrfToken', /*csrfProtection,*/ function (req, res) {
    // check credentials from request.body
    // and then 

    res.render('send', { csrfToken: req.csrfToken() })  //EXCEPTION: csrfToken is not a function 
})

app.post('/process', parseForm, csrfProtection, function (req, res) {
    res.send('data is being processed')
})

I'm facing the egg-hen problem: if I enable csrfProtection, I cannot get into the endpoint's code without the token, but if I disable it, req.csrfToken becomes undefined.

I need the gerCsrfToken endpoint to be POST, because I don't want to expose password as url parameter.

Upvotes: 2

Views: 969

Answers (1)

Dan
Dan

Reputation: 57881

Question was answered by csurf maintainer, thanks for a quick response!

https://github.com/expressjs/csurf/issues/133

The (tricky) solution is to ignore POST method for this particular endpoint

app.post('/authenticate', csrf({ cookie: true, ignoreMethods: ['POST'] }), function (req, res) {

Upvotes: 3

Related Questions