CSRF Protection
Cross-Site Request Forgery (CSRF or XSRF) is a type of attack relying on performing actions by the attacker on behalf of currently authenticated user using unsecured endpoints.
How Do CSRF Attacks Work?
Without CSRF protection, the attacker could prepare a simple HTML form pointing to your application.
views/login.atom.html
<form action="https://my-app.com/posts/create" method="post"> <input type="text" name="body" value="I don't like ice cream"> </form>
When the form is submitted (for example, when attacker sends the user a link to this form and they open it), the authenticated user wil publish a new post without their knowledge.
Token Protection
To prevent CSRF attacks, Entropy generates a unique token for every user session to protect your application.
Anytime you define forms with method other than GET
and HEAD
, you have to add a hidden _token
field containing generated token. Otherwise, you won't be able to pass the form and you will get 419 Invalid Token
error.
To add the CSRF token field to your template, just use the @csrf
directive:
views/login.atom.html
<form action="..." method="post"> @csrf ... </form>
When this token is present, an unauthorized user is not able to do anything without user knowledge.