Skip to content
This repository has been archived by the owner on Sep 14, 2022. It is now read-only.

Commit

Permalink
docs: add example of csurf ignoring routes
Browse files Browse the repository at this point in the history
closes #77
closes #79
  • Loading branch information
gabeio authored and dougwilson committed Aug 12, 2015
1 parent d85a93a commit b5dd3e2
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,58 @@ input field named `_csrf`:
</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.

```js
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
Expand Down

0 comments on commit b5dd3e2

Please sign in to comment.