Override protect_from_forgery strategy in controller

I want to create a rails application with two different protect_from_forgery strategies: one for the web application and one for the API.

In my application controller, I have this line of code: protect_from_forgery with: :exceptionto prevent CSRF attacks, it works fine.

In my namespace API I have created api_controller, which is inherited from my application controller, and is the parent class of all other controllers in the API namespace, and I changed the code above: protect_from_forgery with: :null_session.

Unfortunately, I have an error while trying to make a POST request: "Unable to verify the authenticity of the CSRF token."

I don’t want to skip the verify_authenticity_token method in my API controllers, I just want to have two different strategies in my application, so how do I override the protect_from_forgery strategy defined in my application controller?

Edit : Okay, so I eventually did what I didn’t want to do in the first place: change the inheritance of my api_controller: it now inherits from ActionController :: Base and is no longer from my application controller. Now it works, but:

  • This does not answer my question, that is, it overrides the protect_from_forgery strategy.
  • This is NOT DRY, as I need to copy / past what was previously in my controller_ application.

So, if anyone has a real way to rewrite this method, I would appreciate it.

+4
3

, protect_from_forgery with: :exception , API?

skip_before_action :protect_from_forgery
protect_from_forgery with: :null_session

, CSRF- -, API.

+11

- Web App + API. CSRF :

  • protect_from_forgery API
  • API - api.example.com, API -.

:

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception, if: :isWebRequest?

  def isWebRequest?
    request.subdomains[-1] != 'api'
  end

end
+3

Late to the party, but something like this can be done:

class YourCustomStrategy
  def initialize(controller)
  end

  def handle_request
  end
end

And in your ApplicationController or wherever you want:

class ApplicationController < ActionController::Base
 protect_from_forgery with: YourCustomStrategy
end
0
source

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


All Articles