expressjs / csurf

CSRF token middleware
MIT License
2.3k stars 217 forks source link

A way of getting csrfToken through POST request #133

Closed Bogdan-Kalynovskyi closed 6 years ago

Bogdan-Kalynovskyi commented 6 years ago

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.

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

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

naufalkhalid commented 4 years ago

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