0

I'm getting Error: misconfigured csrf when I'm trying to access my login-page. I'm implementing the csurf to a router, but I'm just getting the response statuscode 500.

Implementation:

let router = require("express").Router();

let PostLoginResource = require("./../resources/PostLoginResource");
let RateLimit = require("express-rate-limit");
let csrf = require("csurf");

let csrfProtection = csrf({ cookie: true });

router.route("/login")
    .get(csrfProtection, function(req, res) {
        // Do some stuff
    })

    .post(loginLimiter, function(req, res) {

        PostLoginResource(req, function(success, err) {
            // Do some stuff
        })

    });

I'm starting the session-cookie before I'm using this module in app.js:

// Parse the request body as JSON
app.use(bodyParser.json());

// Parse the URL encoded data
app.use(bodyParser.urlencoded({extended: true}));

// Set up session-cookie
app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    cookie: {secure: true,
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24
    }
}));

Still, this is not working. Anyone knows what the problem is?

3
  • is that path correct: ./../resources/PostLoginResource?
    – Remario
    Commented Mar 1, 2017 at 12:36
  • Yes, otherwise that would be the error-message, not Error: misconfigured csrf
    – Jesper
    Commented Mar 1, 2017 at 12:37
  • well you did got a 500, meaning internal error. incorrect statements causes it.Where did you require the session object>
    – Remario
    Commented Mar 1, 2017 at 12:39

1 Answer 1

1
var cookieParser = require('cookie-parser')

parse cookies we need this because "cookie" is true in csrfProtection

app.use(cookieParser())
2
  • note* The call to app.use(csrf()) must be set after app.use(cookieParser()) AND app.use(session({...}).
    – Remario
    Commented Mar 1, 2017 at 12:48
  • As official description of express session middleware: github.com/expressjs/session 'Since version 1.5.0, the cookie-parser middleware no longer needs to be used for this module to work. This module now directly reads and writes cookies on req/res. Using cookie-parser may result in issues if the secret is not the same between this module and cookie-parser.'
    – Jesper
    Commented Mar 1, 2017 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.