define

CSRF: Cross-Site Request Forgery

Cause of

This starts with the role of cookies. We know that HTTP requests are stateless, but in a real Web application, we need the request to be stateful. For example, we need to remember the status of the login and not log in again for every request. In order to implement this requirement we need cookies.

Cookie on the server side through the Set-Cookie to Set the value to be stored in the Cookie, and then stored in the client (browser). Any subsequent requests to the same domain made by the client will carry information about these cookies.

The problem is that all requests to the same domain will have cookies, but there is no restriction on where the requests are originated.

Let’s take a look at the following scenario:

At this point, we should have a clear understanding of CSRF tokens.

How do you prevent that in Rails

In Rails, the way to prevent this attack is to verify an authenticity token on any non-GET request. This token corresponds to each session, and each time a session is generated, a random token is generated and stored in the session. This token is required when sending requests to the server (not GET).

So the question is how does the front-end code get the token when it sends the request?

In Rails, if you’re using a form helper, the back-end render will read the token from the session and insert it into the form’s hidden field. If you are sending Ajax requests via FE JS, you need to read the token from the meta tag of the layout of this site.

Therefore, a request from a third party site (Site B) will not be able to obtain the token (if it has obtained the token, it means that it has already had a session, so there is no need to send the request through Site B), so the request will fail to pass the verification on the server side.

Additional Information:

Rails has a comparison between request.base_url and request.origin when comparing tokens for consistency. Here base_url refers to the domain address of the request, and origin refers to where the request came from. Please look at the following example: suppose we’re on A site Bhttps://websiteb.com triggered A request to the site Ahttps://websitea.com: POST https://websitea.com/path so at this point in A server: Request. base_url is https://websitea.com request.origin is