If the token is visible in the page source (I.e. hidden input field) wouldn’t this defeat the purpose? The token can just be grabbed from the page source. Maybe I’m overthinking this, but shouldn’t a CSRF token only be generated on successful login?
If the token is visible in the page source (I.e. hidden input field) wouldn’t this defeat the purpose? The token can just be grabbed from the page source. Maybe I’m overthinking this, but shouldn’t a CSRF token only be generated on successful login?
CSRF tokens in the page are compared to CSRF tokens that are associated with a browser (e.g. via a cookie or session).
So consider this attack:
Victim and Good Site are safe.
CSRF tokens should be generated after a session has been established with a client, not necessarily only after authentication. Malicious sites could still get a CSRF token from your site by scraping the page source, as you suggested, but the CSRF token they receive won't be valid for the target user's session.
Another advantage to using CSRF tokens at the session-level is because you could then protect your authentication forms against CSRF attacks as well. You'd need to create a session pre-authentication for this to work.
CSRF tokens are not directly related to authentication, they can be used on any form. The purpose of a CSRF token is to correlate two things:
The general approach is this:
The reason this check matters is that a malicious user can look at a form on your site, copy and manipulate it, and then trick a user into submitting it. To your server, this looks like the user submitted the real form, so without a CSRF check, you would accept the instructions as coming from the victim, rather than the attacker.