3

How can I rescue from an OAuth::Unauthorized exception as raised from OmniAuth in a Ruby on Rails application?

Obviously this:

  rescue_from OAuth::Unauthorized, :with => :unauthorized

won't work as that only catches exception thrown inside Rails and this exception is thrown somewhere else in the rack chain.

In this application the administrators (and not us, the developers) configure the credentials for twitter and facebook, so having the wrong ones is something that can happen and indeed does happen. I'd like to show a better message that "Something went wrong" when that happens.

Update: I also asked on the omniauth google group, so far there are no answers, but if you are reading this question you might want to check it out.

Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

1 Answers1

2

OmniAuth operates from Rack Middleware, so a rescue_from will not affect it because that is a level of abstraction above OmniAuth via ActionController.

This error is usually due to a misconfiguration of your OAuth settings. Basically it is saying that your application is not authorized to authenticate, not that the user's authentication failed.

A configuration error is something you as a developer would want to mitigate, so I'm not sure why you would want to rescue an exception like this.

If you absolutely must rescue this exception, you can override and use middleware that inherits from OmniAuth

module OmniAuth
  module Strategies
    class FacebookWithExceptionHandling < OmniAuth::Strategies::Facebook
      def call
        begin
          super
        raise OmniAuth::Unauthorized => e
          #handle appropriately in rack context here
        end
      end
    end
  end
end

Rails.application.config.middleware.use OmniAuth::Builder do
  provider OmniAuth::Strategies::FacebookWithExceptionHandling, 
    api_key, #your api key 
    secret_key, #your secret key
end
danpickett
  • 2,046
  • 14
  • 18
  • The users are configuring the tokens and keys for twitter and facebook. There's nothing I can't do to avoid them putting the wrong information at some time. I'll update the question to explain this. – Pablo Fernandez Mar 04 '12 at 09:57
  • 1
    ok that makes sense. So since OmniAuth is just rack middleware, you can just override the rack class. I'll update my response above – danpickett Mar 04 '12 at 17:23