Preventing Cross Site Request Forgery CSRF
suggest changeCSRF is an attack that makes an authenticated user perform an action they did not intend. The browser sends cookies with a request even when another site triggered it.
The csurf package used below is archived and had security issues. Do not depend on it for a new app. The pattern is still right: put a token in the form and reject a POST that does not send it back. res.render also needs a view engine, which this snippet does not configure.
Example
var express = require('express')
var cookieParser = require('cookie-parser') //for cookie parsing
var csrf = require('csurf') //csrf module
var bodyParser = require('body-parser') //for body parsing
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
// parse cookies
app.use(cookieParser())
app.get('/form', csrfProtection, function(req, res) {
// generate and pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('data is being processed')
})
So, when we access GET /form, it will pass the csrf token csrfToken to the view.
Now, inside the view, set the csrfToken value as the value of a hidden input field named _csrf.
For example, in a Handlebars template:
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
Name: <input type="text" name="name">
<button type="submit">Submit</button>
</form>
For example, in a Pug template (Pug was formerly Jade):
form(action="/process" method="post")
input(type="hidden", name="_csrf", value=csrfToken)
span Name:
input(type="text", name="name", required=true)
br
input(type="submit")
For example, in an EJS template:
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
Name: <input type="text" name="name">
<button type="submit">Submit</button>
</form>
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents