Recently, I started developing an app that consists of Vue for the front and Ruby for the back. Since the front desk became Vue, I decided to write CSRF measures myself, but I was curious about the mechanism of CSRF measures that Rails would do without permission, so I investigated it.
--Abbreviation for Cross Site Request Forgeries. --By following a link on another site, the user launches an attack on the logged-in web application. Request Forgeries because it impersonates the request. The specific flow is described below.
ex)
Basically, it is necessary to issue a security token for operations other than GET (query, read, search).
form_with, form_tag
Rails includes a security token as standard in the information sent from the form tag. If you use a helper such as form_with, it will automatically issue and verify tokens as shown below.
<input type="hidden" name="authenticity_token" ...>
protect_from_forgery
By writing on the controller side, it will check if the security token is correct for the action. If you want to change the data from the client side, you need to use except and take CSRF measures by other methods.
Rails also provides some security token support in Ajax. When making an Ajax request by JavaScript, it seems that Rails issues a security token first and sends it by JS. (HTTP header called X-CSRF-Token)
To issue a security token on the Rails side, call csrf_meta_tags
.
When you include a security token in Ajax, it will be done automatically in the Ajax request using rails-ujs.
I'm grateful that Rails did a good job behind the scenes. Next, I would like to summarize the CSRF measures when a request is skipped from the client side.
Rails Security Guide (https://railsguides.jp/security.html)
Recommended Posts