Understanding the Rails Authenticity Token
When user create, update, or destroy a resource, the Rails app creates a random
authenticity_token, stores this token in the session, and places in a hidden in the form. Rails looks for the
authenticity_token, they match the request is allowed to continue.
why it appear:
The authenticity token is stored in the session, the client cannot know its value. some evil code was service B, it might send a request to service A , and ask to delete your account, by sending a request to
You can seen in below link: API docs
CSRF protection is turned on with the protect_from_forgery method.The token parameter is named authenticity_token by default. The name and value of this token including csrf_meta_tags in the HTML
The Rails only verifies not idempotent methods (POST, PUT/PATCH and DELETE). GET request are not checked for authenticity token. GET requests is idempotent and should not create, alter, or destroy resources at the server.
Using authenticity_token to protect your not idempotent methods (POST, PUT/PATCH, and DELETE) not to allow any GET requests that could potentially modify on the server.
Here is the solution:
There authenticity token is designed your form is being submitted from your website. In generated from the machine runs with a unique identifier that only your machine so helping prevent cross-site request forgery attacks.
AJAX script :
<%= form_authenticity_token %>
Briefly Explain in below link: documentation
This will be the simple Answers:
CSRF: Cross-Site Request Forgery
- Visit your bank’s site, log in.
- Then visit the attacker’s site.
- Attacker’s page includes form with same fields as the bank’s “Transfer Funds” form.
- When form gets submitted, browser includes your cookies.
- Bank transfers money to attacker’s account.
- The form can be in an iframe that is invisible, so you never know the attack occurred.
- Server can mark forms that came from the server itself.
- Every form must contain an additional authentication token as a hidden field.
- Token must be unpredictable .
- Server provides valid token in forms in its pages.
- Server checks token when form posted, rejects forms without proper token.
- Example token: session identifier encrypted with server secret key.
- Authenticity_token input field in every form.