How can Cross-Site Request Forgery (CSRF) attacks be mitigated when using JWTs stored in cookies?

Node.js interview question for Advanced practice.

Answer

By setting the SameSite=Strict or SameSite=Lax attribute on the cookie containing the JWT.

Explanation

CSRF attacks work because browsers automatically include cookies on requests to a domain, even if the request originates from a different, malicious site. The SameSite cookie attribute is the primary defense against this. Setting it to Strict prevents the browser from sending the cookie on any cross-site request. Lax provides a balance, allowing the cookie on top-level navigations (e.g., clicking a link) but not on cross-site form submissions or AJAX requests. Storing the token in localStorage (A) opens it up to XSS attacks, which is often a worse vulnerability.

Related Questions