Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
The csurf npm package is a middleware for Node.js that provides Cross-Site Request Forgery (CSRF) protection. It helps secure web applications by ensuring that state-changing requests are made by authenticated users and not by malicious actors.
Basic CSRF Protection
This code demonstrates how to set up basic CSRF protection using the csurf middleware in an Express application. It includes setting up the middleware, generating a CSRF token, and embedding it in a form.
const express = require('express');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const app = express();
const csrfProtection = csrf({ cookie: true });
app.use(cookieParser());
app.use(csrfProtection);
app.get('/form', (req, res) => {
res.send(`<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="${req.csrfToken()}">
<button type="submit">Submit</button>
</form>`);
});
app.post('/process', (req, res) => {
res.send('Form processed');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
CSRF Protection with Session Storage
This example shows how to use csurf with session storage for CSRF protection. The session middleware is used to store the CSRF token, which is then embedded in a form and validated upon form submission.
const express = require('express');
const session = require('express-session');
const csrf = require('csurf');
const app = express();
const csrfProtection = csrf();
app.use(session({ secret: 'mySecret', resave: false, saveUninitialized: true }));
app.use(csrfProtection);
app.get('/form', (req, res) => {
res.send(`<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="${req.csrfToken()}">
<button type="submit">Submit</button>
</form>`);
});
app.post('/process', (req, res) => {
res.send('Form processed');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Helmet is a collection of middleware functions that help secure Express applications by setting various HTTP headers. While it does not provide CSRF protection directly, it offers a range of other security features such as XSS protection, content security policy, and more. It can be used alongside csurf for comprehensive security.
Lusca is another security middleware for Express that provides various security features, including CSRF protection. It is similar to csurf but also includes additional features like XSS protection, HSTS, and CORS. Lusca can be a more comprehensive solution if you need multiple security features in one package.
Node.js CSRF protection middleware.
Requires either a session middleware or cookie-parser to be initialized first.
false
value,
then you must use cookie-parser
before this module.If you have questions on how this module is implemented, please read Understanding CSRF.
$ npm install csurf
var csurf = require('csurf')
Create a middleware for CSRF token creation and validation. This middleware
adds a req.csrfToken()
function to make a token which should be added to
requests which mutate state, within a hidden form field, query-string etc.
This token is validated against the visitor's session or csrf cookie.
The csurf
function takes an optional options
object that may contain
any of the following keys:
Determines if the token secret for the user should be stored in a cookie
or in req.session
. Defaults to false
.
When set to true
(or an object of options for the cookie), then the module
changes behavior and no longer uses req.session
. This means you are no
longer required to use a session middleware. Instead, you do need to use the
cookie-parser middleware in
your app before this middleware.
When set to an object, cookie storage of the secret is enabled and the
object contains options for this functionality (when set to true
, the
defaults for the options are used). The options may contain any of the
following keys:
key
- the name of the cookie to use to store the token secret
(defaults to '_csrf'
).path
- the path of the cookie (defaults to '/'
).An array of the methods for which CSRF token checking will disabled.
Defaults to ['GET', 'HEAD', 'OPTIONS']
.
Determines what property ("key") on req
the session object is located.
Defaults to 'session'
(i.e. looks at req.session
). The CSRF secret
from this library is stored and read as req[sessionKey].csrfSecret
.
If the "cookie" option is not false
, then this option does
nothing.
Provide a function that the middleware will invoke to read the token from
the request for validation. The function is called as value(req)
and is
expected to return the token as a string.
The default value is a function that reads the token from the following locations, in order:
req.body._csrf
- typically generated by the body-parser
module.req.query._csrf
- a built-in from Express.js to read from the URL
query string.req.headers['csrf-token']
- the CSRF-Token
HTTP request header.req.headers['xsrf-token']
- the XSRF-Token
HTTP request header.req.headers['x-csrf-token']
- the X-CSRF-Token
HTTP request header.req.headers['x-xsrf-token']
- the X-XSRF-Token
HTTP request header.The following is an example of some server-side code that generates a form that requires a CSRF token to post back.
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.get('/form', csrfProtection, function(req, res) {
// 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')
})
Inside the view (depending on your template language; handlebars-style
is demonstrated here), set the csrfToken
value as the value of a hidden
input field named _csrf
:
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
Favorite color: <input type="text" name="favoriteColor">
<button type="submit">Submit</button>
</form>
Note CSRF checks should only be disabled for requests that you expect to come from outside of your website. Do not disable CSRF checks for requests that you expect to only come from your website. An existing session, even if it belongs to an authenticated user, is not enough to protect against CSRF attacks.
The following is an example of how to order your routes so that certain endpoints do not check for a valid CSRF token.
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// create express app
var app = express()
// create api router
var api = createApiRouter()
// 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 }))
app.get('/form', function(req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', function(req, res) {
res.send('csrf was required to get here')
})
function createApiRouter() {
var router = new express.Router()
router.post('/getProfile', function(req, res) {
res.send('no csrf to get here')
})
return router
}
When the CSRF token validation fails, an error is thrown that has
err.code === 'EBADCSRFTOKEN'
. This can be used to display custom
error messages.
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var express = require('express')
var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(csrf({ cookie: true }))
// error handler
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
// handle CSRF token errors here
res.status(403)
res.send('form tampered with')
})
FAQs
CSRF token middleware
We found that csurf demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.