How Csurf Middleware Validates Tokens?

- 1 answer

I am testing NodeJS express app that uses csurf package along with express-session package.


While testing, i have to make requests that should include csrf token in them but because i don't really understand how csurf middleware validates csrf tokens in incoming requests, that is causing a lot of problems in testing the app.


Can someone explain in simple terms, how csurf middleware validates csrf tokens when using csurf middleware with express-session package? How it validates token when it receives it in a request? Should tokens be sent in headers or in request body? Is new token created every time a new page is rendered or do we have once token per user session?

I also want to know how that the token validation process will change when using csurf middleware with cookie-parser package?



The csurf works by storing a token secret into either the session (in the case of express-session) or directly into cookie (case of cookie-parser). The server side should then render the website with a dynamically generated (per request) token via req.csrfToken(). This csrf token is derived from token secret and can be verified later.

When calling csurf protected endpoints, this token should then be included by client via body or header (see the default values here). The middleware will then fetch the token secret from either the session or cookie, then verify it is a valid token generated by the secret owned by the user. If the verification fails, it will throw a csrf error.

Since csrf token generated is not time sensitive, for unit testing you can actually hardcode a same token secret into session or cookie, call req.csrfToken() once to receive a valid token, then keep on reusing the same token for every test.