ruby-on-railsauthenticationsessioncsrfauthenticity-token

protect_from_forgery and login forms


Reading about how protect_from_forgery works, I came across multiple articles such as this one which explains that the authenticity_token is bound to the user's session. All clear so far. But a question came up, how does protect_from_forgery work with login forms since it's supposed there isn't a user's session yet? I'd think protect_from_forgery could be disabled for the sessions#create action but the scenario that @wjordan proposes here makes sense to me, but I can't figure out how it works.


Solution

  • Users visiting a website do have a session before logging in however it is an unauthenticated session (also referred to as a pre-session). The CSRF is bound to that session. If you are using Devise, once you log in you will get another session. A good explainer on the types of attacks this mitigates is provided here https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#login-csrf The linked paper within the article has detailed examples which are great!