CSRF protection with double-submit cookie

11261
0

Session-based apps still need CSRF protection even when the API is ‘JSON’. I like the double-submit cookie approach: set a CSRF token cookie, require the client to echo it in x-csrf-token, and verify they match. The reason I prefer this is that it doesn’t require server-side CSRF state and it plays nicely with otherwise stateless services. The gotcha is cookie flags: the CSRF cookie must be readable by JS (not HttpOnly), while the session cookie should stay HttpOnly. I also enforce SameSite settings and validate Origin/Referer for extra defense. It’s a small amount of code that blocks a surprisingly common class of attacks.