Giter Site home page Giter Site logo

csurf's Introduction

csurf

NPM Version NPM Downloads Build status Test coverage Gratipay

Node.js CSRF protection middleware.

Requires either a session middleware or cookie-parser to be initialized first.

If you have questions on how this module is implemented, please read Understanding CSRF.

Installation

$ npm install csurf

API

var csurf = require('csurf')

csurf([options])

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.

Options

The csurf function takes an optional options object that may contain any of the following keys:

cookie

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 '/').
  • any other res.cookie option can be set.
ignoreMethods

An array of the methods for which CSRF token checking will disabled. Defaults to ['GET', 'HEAD', 'OPTIONS'].

sessionKey

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.

value

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.

Example

Simple express example

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>

Ignoring Routes

CSRF should be disabled for API areas of websites where requests are all going to be fully authenticated and should be rate limited. The following is an example of how to ignore API routing using routers & express.

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())

// create api router
var api = createApiRouter()

// mount api before csrf is appended to the app stack
app.use('/api', api)

// now add csrf, after the "/api" was mounted
app.use(csrfProtection)

app.get('/form', function(req, res) {
  // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() })
})

app.post('/process', parseForm, 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
}

Custom error handling

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')
})

License

MIT

csurf's People

Contributors

dougwilson avatar jonathanong avatar mscdex avatar fishrock123 avatar rdegges avatar alvarotrigo avatar gabeio avatar jamielinux avatar juliangruber avatar monsur avatar sahat avatar valango avatar freewil avatar

Watchers

James Cloos avatar Brian Fang avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.