Reputation: 6231
I building a REST API based on Rails 4.
To prevent from cross-site request forgery attacks, I added a CSRF token inside a custom HTTP header that is needed to perform requests such as POST, DELETE, etc.
I know Rails 4 also provides a protect_from_forgery
method with a special option for APIs: with: :null_session
.
So I think that, given it's a best practice, this new Rails method should be present at the top of my ApplicationController
.
But in the same time, I'm also wondering why I should add it... if it is not necessary. Because as I said, my requiring a CSRF token inside a custom HTTP header.
Could you give me the benefits of adding this Rails feature? Thanks a lot.
Upvotes: 4
Views: 539
Reputation: 4653
protect_form_forgery
just adds a before action to the controller which checks if the authenticity_token
is valid.
The :with
parameter specifies how the controller should behave if the token is invalid.
with: :exception
: raises an exception in the controller which can by catched.with: :null_session
: resets the session itself. This means the complete session will be deleted. In other words the session cookie will be reset. For example an user_id
stored in the session won't be available anymore (puts session[:user_id] # => nil
). So you always have to provide a token or any other authentication, which is perfectly fine for an API.You can also remove protect_from_forgery
if you don't use session
.
Upvotes: 2