-
-
Notifications
You must be signed in to change notification settings - Fork 219
csrf always fails #52
Comments
You cannot use both Simply remove one or the other and it works fine. Your |
I removed the |
Make sure that the cookies that are set when you call register you include in your response with the token. |
I'm pulling down and running your app now. |
The issue is to use the |
Clearly, the documentation needs to be expanded to explain that. |
Yes, that was the problem, thanks! |
So, this means we can't use the "recommend way to use body-parser with express" anymore right? |
@ricardograca yes you can; you just need to move down this middleware into each of your routes, after the body parser, rather than using this module globally (or don't pass the token in the body, but in the URL, a header, or somewhere else). Example: var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
var session = require('express-session')
// setup body parsing
var parseJson = bodyParser.json()
var parseUrlencoded = bodyParser.urlencoded()
// create a group
var parseBody = [parseJson, parseUrlencoded]
// setup csrf
var csrfProtection = csurf()
// setup express
var app = express()
// i put this _before_ express-session to not invoke session
// lookups for static files
app.use(express.static(__dirname + '/public'))
// user sessions
app.use(session({
secret: 'keyboard cat'
}))
app.post('/register', parseBody, csrfProtection, function (req, res) {
var email = req.body.email
var password = req.body.password
console.log('login done')
console.log(req.body)
res.json({"done":"done"})
})
app.get('/register', csrfProtection, function (req, res) {
res.json({"csrf": req.csrfToken()});
})
// handle csrf errors specifically
app.use(function(err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err);
res.status(403).json({"error": "session has expired or tampered with"});
});
app.listen(3000) |
@dougwilson That makes sense, many thanks. |
The readme should be clearer now :) |
The document says:
_csrf parameter in req.body generated by the body-parser middleware.
From the client, I have done a POST and the request payload is:
{"email":"testing@blah.com","password":"asdfas","_csrf":"Cn72pjW6-8PQ43dGXIAjslG488tFfAAgzX0s"}
But I always get a
403
error "session has expired or tampered with".This is the expressjs app:
The csrf token is retrieved when the client does a GET
/register
, which sets the csrf token on the form. When the form is submitted, the request payload is sent but denied by csurf. I'm still not clear on what is needed after reading the doc. Am I missing something?The text was updated successfully, but these errors were encountered: