How csurf middleware validates tokens? How csurf middleware validates tokens? express express

How csurf middleware validates tokens?


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.


Whether or not to issue a CSRF token per-request or per user session seems to be an area of debate, and even the top two answers on this stackoverflow security question disagree on the matter.

The Bottom Line:

We should always follow OWASP's recommendations which states that per request CSRF tokens are more secure, but not necessary and can cause other problems.

CSRF tokens should be generated on the server-side. They can be generated once per user session or for each request. Per-request tokens are more secure than per-session tokens as the time range for an attacker to exploit the stolen tokens is minimal. However, this may result in usability concerns.

...

It is worth noting though that the back button issue may not be a problem with csurf since it uses secret mechanism to generate/validate tokens (which allows old tokens to validate).

Finally, if you are building an SPA:

The csurf documentation says to only send down the CSRF token once on the route that renders the page