Proper use of protect_from_forgery in a Rails application serving the web interface and API

I am developing a Rails 4 application that serves a mobile application through an API and has a web interface for administrators to manage the application. There are also several web pages that users will see (successful email confirmation and password reset).

I created two sets of controllers: one set is inherited from APIController, and the other from AdminController. Both of them inherit from ApplicationController. The remaining controller responsible for custom web pages is also inherited from ApplicationController.

Given this scheme, I'm not sure how to properly implement CSRF protection with _from_forgery protection. I currently have the following:

class ApplicationController < ActionController::Base # ... end module API class APIController < ApplicationController protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' } # ... end end module Admin class AdminController < ApplicationController protect_from_forgery with: :exception # ... end end class UsersController < ApplicationController protect_from_forgery with: :exception # ... end 

So my question is: is this correct? Is there any way to improve it? Is validation in APIController pointless since all API requests will be JSON only?

Brakeman complained that there was no protect_from_forgery call in the ApplicationController, but it might not see the calls in subclasses.

Thanks in advance!

+5
source share
1 answer

You can see here on your page (gigub) , which only checks for ApplicationController

Admin and Users controllers work fine with protect_from_forgery with: :exception

The default behavior for Rails 4 for protect_from_forgery is :null_session , you can remove the with: option if you want.

On the improvement, I would implement a way to save the token in the user and match for each request, so the user requesting the API will have to send their token to each request. By doing this, you avoid the need to obtain a CSRF token, and then send a request with that token. For example, for mobile users, this is one additional request, where you can solve by simply saving the correct token. If someone receives this token, he can go through as a user and change the data. But you can find more ways to make it safer.

CSRF can happen if you save the token in sessions or cookies, you will have to take care of this yourself if you decide to save this.

If you intend to use the API for mobile phones, save the token (in the first of my strategies) on your mobile device (memory or local db), and it will be more secure.

+2
source

Source: https://habr.com/ru/post/1237808/


All Articles