Skip to content

Interaction with authorization mechanisms

Bjørn Trondsen edited this page Apr 29, 2022 · 11 revisions

The error responses are rendered through the standard Rails stack, so if you're using an authorization mechanism like declarative_authorization, and have it set up to block everything by default, then you will need to grant access to actions in the error_response_controller. They are called :index and :dummy_action.

config.after_initialize do
  Rails.configuration.to_prepare do
    ErrorResponseController.class_eval do
      skip_authorization_check # CanCan
      skip_before_action :authenticate # custom ApplicationController method
    end
  end
end

Declarative Authorization

For declarative_authorization you can add a line to the after_initialize callback in config/rails_exception_handler.rb:

config.after_initialize do
  ErrorResponseController.send(:filter_access_to, :all)
end

And then an authorization rule:

role :guest do
  has_permission_on(:error_response, :to => [:index, :dummy_action])
end

CanCan

For CanCan, the callback content can be set as following:

config.after_initialize do
  ErrorResponseController.send(:skip_authorize_resource)
end

or more precisely

config.after_initialize do
  ErrorResponseController.send(:skip_authorize_resource, :only => [:index, :dummy_action])
end

Which will grant access to any user.

If you are using another authorization mechanism or know how to define more precisely CanCan authorizations, I'd appreciate if you'd update this entry with instructions on how to configure it for the exception handler.

Pundit

config.after_initialize do
  ErrorResponseController.send(:after_action, :verify_authorized, except: [:index, :dummy_action])
  ErrorResponseController.send(:after_action, :verify_policy_scoped, except: [:index, :dummy_action])
end