Skip to content

Commit

Permalink
Merge pull request #2259 from ministryofjustice/replace-csurf
Browse files Browse the repository at this point in the history
Moving away from csurf and to csrf-sync
  • Loading branch information
aliuk2012 authored Dec 19, 2024
2 parents 62eda52 + 0ad20d4 commit a1670bd
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 107 deletions.
111 changes: 8 additions & 103 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
"compression": "^1.7.4",
"connect-flash": "^0.1.1",
"connect-redis": "^7.0.0",
"csurf": "^1.11.0",
"csrf-sync": "^4.0.3",
"date-fns": "^3.0.0",
"dotenv": "^16.4.4",
"express": "^4.21.0",
Expand Down Expand Up @@ -173,7 +173,6 @@
"@types/compression": "^1.7.2",
"@types/connect-flash": "0.0.40",
"@types/cookie-session": "^2.0.44",
"@types/csurf": "^1.11.2",
"@types/express-session": "^1.17.5",
"@types/http-errors": "^2.0.0",
"@types/jest": "^29.0.0",
Expand Down
14 changes: 12 additions & 2 deletions server/middleware/setUpCsrf.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Router } from 'express'
import csurf from 'csurf'
import { csrfSync } from 'csrf-sync'

const testMode = process.env.NODE_ENV === 'test'

Expand All @@ -8,7 +8,17 @@ export default function setUpCsrf(): Router {

// CSRF protection
if (!testMode) {
router.use(csurf())
const {
csrfSynchronisedProtection, // This is the default CSRF protection middleware.
} = csrfSync({
// By default, csrf-sync uses x-csrf-token header, but we use the token in forms and send it in the request body, so change getTokenFromRequest so it grabs from there
getTokenFromRequest: req => {
// eslint-disable-next-line no-underscore-dangle
return req.body._csrf
},
})

router.use(csrfSynchronisedProtection)
}

router.use((req, res, next) => {
Expand Down

0 comments on commit a1670bd

Please sign in to comment.