expressjs / csurf

CSRF token middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A way of getting csrfToken through POST request

Bogdan-Kalynovskyi opened this issue · comments

Here's the example from official docs, except one difference: xsrfToken is sent 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')

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

var app = express()
app.use(cookieParser())

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

    res.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 access the endpoint without the token, but if I disable it, req.csrfToken becomes undefined.

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

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

The middleware instance you mount on your POST route should just have POST included in your ignoreMethods option.

It still does not validate the token in the subsequent request since the function returns a different value