I am confused about this. Behavior and properties of both seem identical: both are generated server-side, should be cryptographically secure, with the lifetime not to exceed session duration. If all of these requirements are met, defense in-depth and historical reasons aside, what does anti-CSRF token accomplish that session ID does not?
-
[You seem to confuse between CSRF Token and Session ID.](https://security.stackexchange.com/questions/19128/csrf-cookie-vs-session-based-tokens) – Rahul Dec 16 '22 at 16:46
2 Answers
Session ID is often stored in a cookie in the user's browser, and it is sent in each subsequent request.
An attacker can trick the user to make a request to the web application, using for example a phishing website.
The session ID (stored in the cookie) will be sent automatically, even if the attacker's website is in a different domain than the web application (hence CROSS SITE!)
If the web application doesn't have any CSRF defence mechanism (e.g. anti-CSRF token), it cannot distinguish if the request was intentional or not.
If the web app uses anti-CSRF token, the attacker cannot predict it, and cannot formulate his phishing website to make a valid request.
- 54
- 3
[...] with the lifetime not to exceed session duration [...]
This depends on the CSRF defense employed; people prefer to have a CSRF token used throughout the lifespan of a session for usability reasons. However, per-request tokens can be used too.
CSRF and session tokens can be different because:
Session tokens should be sent with every request made. For this reason they are usually set as cookies. However, they should not be accessible from javascript for security reasons and, thus, should be protected by the
HttpOnly
flag (andSecure
, hopefully). On the other hand, depending on how you implement the CSRF counter measure (e.g. double submit cookie), you may need to read the CSRF token from javascript, which means that if you send the token to the client as a cookie, it shouldn't have theHttpOnly
flag set (that's a problem for sessions, as we saw)Session tokens as cookies allow CSRF to take place. If you don't want to employ separate CSRF tokens, then your session token should not be sent as a cookie but rather exchanged as a request parameter/header (e.g. see a relevant answer for JWTs & CSRF). People may not want to do this, either because of personal preference or implementation related reasons
Semantically they are different; session tokens are there because they represent identity (authentication - the bearer of the token is authenticated). CSRF tokens are there because they represent permission (authorization - the request is authorized); as such, people tend to deal with them separately to allow for flexibility
As stated earlier, CSRF tokens can be issued and used per-request. So, you need different tokens for CSRF and sessions due to the difference in their lifespan
- 1,451
- 1
- 14