Alyssa Nicoll 0ad841a423 init commit | il y a 9 ans | |
---|---|---|
.. | ||
node_modules | il y a 9 ans | |
HISTORY.md | il y a 9 ans | |
LICENSE | il y a 9 ans | |
README.md | il y a 9 ans | |
index.js | il y a 9 ans | |
package.json | il y a 9 ans |
Node.js CSRF protection middleware.
Requires either a session middleware or cookie-parser to be initialized first.
$ npm install csurf
var csrf = require('csurf')
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.
value
a function accepting the request, returning the token.
_csrf
parameter in req.body
generated by the body-parser
middleware._csrf
parameter in req.query
generated by query()
.x-csrf-token
and x-xsrf-token
header fields.cookie
set to a truthy value to enable cookie-based instead of session-based csrf secret storage.
cookie
is an object, these options can be configured, otherwise defaults are used:key
the name of the cookie to use (defaults to _csrf
) to store the csrf secretignoreMethods
An array of the methods CSRF token checking will disabled.
(default: ['GET', 'HEAD', 'OPTIONS']
)Lazy-loads the token associated with the request.
The following is an example of some server-side code that protects all non-GET/HEAD/OPTIONS routes with a CSRF token.
var express = require('express')
var csrf = require('csurf')
var app = express()
app.use(csrf())
// 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('session has expired or form tampered with')
})
// pass the csrfToken to the view
app.get('/form', function(req, res) {
res.render('send', { csrfToken: req.csrfToken() })
})
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>
var express = require('express')
var csrf = require('csurf')
var app = express()
app.use(csrf())
// 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('session has expired or form tampered with')
})