Passing CSRF token to client
bitinn opened this issue · 4 comments
Thx to recent update, my question in #2 are addressed.
I do have 1 more question: is it worth discussing ways of passing CSRF token to client?
- For traditional html form (server-side rendering), no problem, hidden input field with csrf token should do the trick.
- For client-sider rendering, framework must have a way to get the token from somewhere, 2 possible choices are
use a cookie
orput it in a meta tag
, then they can be used to render hidden input field.
I guess both are valid options? though they both appear to have a drawback:
- Updating csrf token will be a problem for single page app, since exposing
/csrf
api is huge no-no. While reusing csrf token multiple times work, it kinda step on the BREACH attack? The best way I can think of is toSet-Cookie
on AJAX response, so that client can re-render input field.
As a side-note: does it mean CSRF token really isn't designed for SPA, but for a Progressive Enhancement model? I mean if you are SPA, you should always use JSON body instead?
If your backend accepts only application/json
and not the other types, then CSRF is not necessary. This is the best way to construct your SPA unless you designed your SPA to fully work in web browsers that have JavaScript disabled.
So for SPA, use JSON body for API interaction when possible; otherwise use an extra Set-Cookie
to expose token to client JS on each request?
Yes, that sounds right to me; if you have to expose a CSRF token to a SPA, a Set-Cookie
is probably the best method, because I don't believe even a CORS response will expose the Set-Cookie
header, which makes it safe even if there is mis-configured CORS on your server :)
Cool, I will close this, @jonathanong if you feel that's a good addition, please add it so no more debate about how to set token properly with AJAX-based service.