Search code examples
javascriptnode.jsformscsrfcsrf-protection

Nodejs make automatic csrf protection


Well i am building simple nodejs cms. My question is simple how can i make automatic CSRF protection? Because i think its dangerous and i can miss this protection in form or route. Is there any way how to automatize this proccess?

At this moment i am using this.

Routes.js

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

// Register
router.get("/register", csrfProtection, shouldNotBeAuthenticated, function (req, res) {
    res.render("../modules/users/views/register", {
        title: 'Register',
        csrfToken: req.csrfToken
    });
});

router.post("/register", parseForm, csrfProtection, authController.user_reigster);

Form

<form method="post" action="/users/register">
  <input type="hidden" name="_csrf" value="{{csrfToken}}">

package CSURF.

Thank for any advice.


Solution

  • I think that you are on the right track.

    The middleware should be applied to ALL POST requests*. An example on the CSURF readme shows the way to do it (worth reading carefully):

    // mount api before csrf is appended to the app stack
    app.use('/api', api)
    
    // now add csrf and other middlewares, after the "/api" was mounted
    app.use(bodyParser.urlencoded({ extended: false }))
    app.use(cookieParser())
    app.use(csrf({ cookie: true }))
    

    You should be using a templating language for the user interface. You should have either a template for forms or a filter that looks for forms which include the CSRF attributes in the form when rendering.

    If you are making AJAX POSTs (XMLHttpRequest), that will also need to be thought through and is well covered on this site.

    * if you have api routes, the should be grouped and excluded from CSRF.