I’ve been finishing up an application that has a number of custom controller actions. All except one action – the approved action – require user authorization before retrieving any information from the database.

Specifically, I wanted to authentication the administrator for all actions except the approved action for both JSON and XML responses (but not HTML responses).

Here’s how to do it in Rails 3:

before_filter :authenticate_admin!, :except => [ :approved ]
before_filter (:only => :approved) do |controller|
     controller.send :authenticate_admin! unless controller.request.format.json? || controller.request.format.xml?
end