How to rescue from a OAuth::Unauthorized exception in a Ruby on Rails application?

跟風遠走 提交于 2019-12-07 13:04:57

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/9227440/how-to-rescue-from-a-oauthunauthorized-exception-in-a-ruby-on-rails-applicatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!