问题描述
如何从Ruby on Rails应用程序中的OmniAuth引发的OAuth ::未经授权的异常中拯救?
显然这是:
rescue_from OAuth ::未经授权, => :未经授权的
将无法正常工作,因为它仅捕获Rails中抛出的异常,并将此异常抛出其他位置在这个应用程序中,管理员(而不是我们的开发人员)配置twitter和Facebook的凭据,所以有错误的是可以发生,确实发生了。我想显示一个更好的消息,发生了什么事情,当这种情况发生。
更新:我也上询问,到目前为止还没有答案,但如果你正在阅读这个问题你可能想检查出来。
OmniAuth从Rack Middleware运行,所以rescue_from不会影响它,因为这是通过ActionController在OmniAuth上方的抽象级别。
此错误通常是由于您的OAuth设置配置错误。基本上说,您的应用程序没有授权进行身份验证,而不是用户的身份验证失败。
配置错误是开发人员想要减轻的问题,所以我不知道为什么要拯救这样的异常。
如果您绝对必须拯救此异常,您可以覆盖并使用从OmniAuth继承的中间件
module OmniAuth
module Strategies
class FacebookWithExceptionHandling< OmniAuth :: Strategies :: Facebook
def call
begin
super
raise OmniAuth :: Unauthorized => e
#handle适用于机架上下文
end
end
end
end
end
Rails.application.config .middleware.use OmniAuth :: Builder do
provider OmniAuth :: Strategies :: FacebookWithExceptionHandling,
api_key,#your api key
secret_key,#你的秘密密钥
end
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.
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
这篇关于如何从Ruby on Rails应用程序中的OAuth ::未经授权的异常中拯救?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!