Gathering detailed insights and metrics for csurf
Gathering detailed insights and metrics for csurf
Gathering detailed insights and metrics for csurf
Gathering detailed insights and metrics for csurf
npm install csurf
Typescript
Module System
Min. Node Version
Node Version
NPM Version
97
Supply Chain
99
Quality
74.5
Maintenance
50
Vulnerability
100
License
Total Downloads
165,482,240
Last Day
37,170
Last Week
436,133
Last Month
2,424,947
Last Year
24,976,773
2,303 Stars
320 Commits
221 Forks
37 Watching
2 Branches
41 Contributors
Latest Version
1.11.0
Package Id
csurf@1.11.0
Size
8.17 kB
NPM Version
6.13.4
Node Version
13.6.0
Publised On
19 Jan 2020
Cumulative downloads
Total Downloads
Last day
-61.8%
37,170
Compared to previous day
Last week
-17.1%
436,133
Compared to previous week
Last month
-2.5%
2,424,947
Compared to previous month
Last year
17.7%
24,976,773
Compared to previous year
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.
This is a Node.js module available through the
npm registry. Installation is done using the
npm install
command:
1$ npm install csurf
1var 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
. Storing the token secret in a cookie implements
the double submit cookie pattern.
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 '/'
).signed
- indicates if the cookie should be signed (defaults to false
).secure
- marks the cookie to be used with HTTPS only (defaults to
false
).maxAge
- the number of seconds after which the cookie will expire
(defaults to session length).httpOnly
- flags the cookie to be accessible only by the web server
(defaults to false
).sameSite
- sets the same site policy for the cookie(defaults to
false
). This can be set to 'strict'
, 'lax'
, 'none'
, or true
(which maps to 'strict'
).domain
- sets the domain the cookie is valid on(defaults to current
domain).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.
1var cookieParser = require('cookie-parser') 2var csrf = require('csurf') 3var bodyParser = require('body-parser') 4var express = require('express') 5 6// setup route middlewares 7var csrfProtection = csrf({ cookie: true }) 8var parseForm = bodyParser.urlencoded({ extended: false }) 9 10// create express app 11var app = express() 12 13// parse cookies 14// we need this because "cookie" is true in csrfProtection 15app.use(cookieParser()) 16 17app.get('/form', csrfProtection, function (req, res) { 18 // pass the csrfToken to the view 19 res.render('send', { csrfToken: req.csrfToken() }) 20}) 21 22app.post('/process', parseForm, csrfProtection, function (req, res) { 23 res.send('data is being processed') 24})
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
:
1<form action="/process" method="POST"> 2 <input type="hidden" name="_csrf" value="{{csrfToken}}"> 3 4 Favorite color: <input type="text" name="favoriteColor"> 5 <button type="submit">Submit</button> 6</form>
When accessing protected routes via ajax both the csrf token will need to be passed in the request. Typically this is done using a request header, as adding a request header can typically be done at a central location easily without payload modification.
The CSRF token is obtained from the req.csrfToken()
call on the server-side.
This token needs to be exposed to the client-side, typically by including it in
the initial page content. One possibility is to store it in an HTML <meta>
tag,
where value can then be retrieved at the time of the request by JavaScript.
The following can be included in your view (handlebar example below), where the
csrfToken
value came from req.csrfToken()
:
1<meta name="csrf-token" content="{{csrfToken}}">
The following is an example of using the
Fetch API to post
to the /process
route with the CSRF token from the <meta>
tag on the page:
1// Read the CSRF token from the <meta> tag 2var token = document.querySelector('meta[name="csrf-token"]').getAttribute('content') 3 4// Make a request using the Fetch API 5fetch('/process', { 6 credentials: 'same-origin', // <-- includes cookies in the request 7 headers: { 8 'CSRF-Token': token // <-- is the csrf token as a header 9 }, 10 method: 'POST', 11 body: { 12 favoriteColor: 'blue' 13 } 14})
Many SPA frameworks like Angular have CSRF support built in automatically.
Typically they will reflect the value from a specific cookie, like
XSRF-TOKEN
(which is the case for Angular).
To take advantage of this, set the value from req.csrfToken()
in the cookie
used by the SPA framework. This is only necessary to do on the route that
renders the page (where res.render
or res.sendFile
is called in Express,
for example).
The following is an example for Express of a typical SPA response:
1app.all('*', function (req, res) { 2 res.cookie('XSRF-TOKEN', req.csrfToken()) 3 res.render('index') 4})
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.
1var cookieParser = require('cookie-parser') 2var csrf = require('csurf') 3var bodyParser = require('body-parser') 4var express = require('express') 5 6// create express app 7var app = express() 8 9// create api router 10var api = createApiRouter() 11 12// mount api before csrf is appended to the app stack 13app.use('/api', api) 14 15// now add csrf and other middlewares, after the "/api" was mounted 16app.use(bodyParser.urlencoded({ extended: false })) 17app.use(cookieParser()) 18app.use(csrf({ cookie: true })) 19 20app.get('/form', function (req, res) { 21 // pass the csrfToken to the view 22 res.render('send', { csrfToken: req.csrfToken() }) 23}) 24 25app.post('/process', function (req, res) { 26 res.send('csrf was required to get here') 27}) 28 29function createApiRouter () { 30 var router = new express.Router() 31 32 router.post('/getProfile', function (req, res) { 33 res.send('no csrf to get here') 34 }) 35 36 return router 37}
When the CSRF token validation fails, an error is thrown that has
err.code === 'EBADCSRFTOKEN'
. This can be used to display custom
error messages.
1var bodyParser = require('body-parser') 2var cookieParser = require('cookie-parser') 3var csrf = require('csurf') 4var express = require('express') 5 6var app = express() 7app.use(bodyParser.urlencoded({ extended: false })) 8app.use(cookieParser()) 9app.use(csrf({ cookie: true })) 10 11// error handler 12app.use(function (err, req, res, next) { 13 if (err.code !== 'EBADCSRFTOKEN') return next(err) 14 15 // handle CSRF token errors here 16 res.status(403) 17 res.send('form tampered with') 18})
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
Found 1/30 approved changesets -- score normalized to 0
Reason
project is archived
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-12-23
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More