[RUBY] Rails CSRF measures and html files under public

Environment and error message

I'm trying to POST data from an html file (static file) under public without using Rails ERb.

Terminal.


Can't verify CSRF token authenticity.

The point is, "I played the request because it is different from the security token I expected."

What is CSRF?

Abbreviation for cross-site request forgery, one of cheating.

The act of an attacker sending a request to a target site by having the victim click a link or visit a page. In other words, the attacker can authenticate himself as a valid request and tamper with the victim's account information.

Therefore, Rails automatically takes measures to prevent malicious things from being mistaken for normal requests.

Rails measures

Rails already has the CSRF countermeasure code automatically embedded in application_controller.

application.controller.rb


protect_from_forgery with: :exception

It introduces a required security token that is automatically included in all Rails-generated forms and Ajax requests.

If the security token does not match the expected value, an error can occur.

Disable CSRF measures themselves

application_controller.rb


protect_from_forgery with: :null_session

CSRF measures are disabled for all actions. However, this has the problem of being extremely vulnerable to aggression.

Partially exclude security tokens

By excluding only specific actions that receive API from the outside, it is possible to receive data from the client while ensuring security.

feeds_controller.rb


protect_from_forgery :except => [:create, :index]

def create
end

def index
end

By specifying the action name of the controller, it is now possible to receive data from the html file under public.

I was allowed to reference##

https://qiita.com/chobi9999/items/2b59fdaf3dd8f2ed9268

https://www.transnet.ne.jp/2016/10/26/%E3%80%8Cruby-on-rails%E3%81%AEcsrf%E5%AF%BE%E7%AD%96colnd/

https://railsguides.jp/security.html#%E3%82%AF%E3%83%AD%E3%82%B9%E3%82%B5%E3%82%A4%E3%83%88%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88%E3%83%95%E3%82%A9%E3%83%BC%E3%82%B8%E3%82%A7%E3%83%AA-csrf

Recommended Posts

Rails CSRF measures and html files under public
[Rails] Adding SameSite and Secure attributes ~ Rails security measures ~
html & rails notes
[Rails] When using ajax, be aware of "CSRF measures".