Search code examples
node.jsexpresscsrfcsrf-protection

csrf token using


I'm interested in a protecting of my web application by using generation a csrf token. My question is how do I need to send that token back to a server: using query param or http header x-csrf-token ?

And what is the difference


Solution

  • Since you're using Express, you can use its CSRF middleware (by Connect): http://www.senchalabs.org/connect/csrf.html

    You can checkout the commented source here: https://github.com/senchalabs/connect/blob/master/lib/middleware/csrf.js

    All you need to do is to include that middleware and then in your POST forms (or PUT etc whatever request that mutates state) set the variable _csrf to have the value req.session._csrf.

    Check example here: https://github.com/senchalabs/connect/blob/master/examples/csrf.js

    UPDATE

    Since Connect 2.9.0 you must use req.csrfToken() instead of req.session._csrf

    Full example: https://github.com/senchalabs/connect/blob/master/examples/csrf.js

    Commit: https://github.com/senchalabs/connect/commit/70973b24eb1abe13b2da4f45c1edbb78c611d250

    UPDATE2

    The connect middleware was split into different modules (and associated repos), you can find them all (including the CSRF one) here: https://github.com/senchalabs/connect#middleware