[英]Handling OmniAuth::Strategies::OAuth2::CallbackError in OmniAuth
[英]How to rescue OmniAuth::Strategies::OAuth2::CallbackError?
我正在使用Omniauth构建Rails应用程序以进行登录服务。要对Google进行身份验证,我使用的是OmniAuth Google OAuth2策略 。
当用户点击“允许访问”按钮时,一切正常。但是当用户点击“不再感谢”按钮时,会出现以下错误。
OmniAuth::Strategies::OAuth2::CallbackError
我尝试在应用程序控制器中添加以下救援代码。
class ApplicationController < ActionController::Base
rescue_from OmniAuth::Strategies::OAuth2::CallbackError, :with =>
:omniauth_callback_error_handler
protected
def omniauth_callback_error_handler
redirect_to init_sign_in_users_path
end
end
但没有运气。
任何的想法?
谢谢 :)
您可以以更清晰的方式在omniauth初始化程序中设置on_failure proc:
OmniAuth.config.on_failure = UsersController.action(:oauth_failure)
发生这种情况是因为身份验证发生在中间件中,因此您的控制器不会参与其中。 这是引发异常的地方,被调用的代码就是这个
我认为你可以通过使用这种代码在Omniauth初始化程序中定义回调来处理这种错误
Omniauth.config do |config|
config.on_failure do
# your handling code invoked in the context of a rack app
end
end
否则会有三个月前的提交引入此行为
def redirect_to_failure
message_key = env['omniauth.error.type']
new_path = "#{env['SCRIPT_NAME']}#{OmniAuth.config.path_prefix}/failure?message=#{message_key}"
Rack::Response.new(["302 Moved"], 302, 'Location' => new_path).finish
end
这表明错误会导致用户被重定向到/auth/failure
并显示错误消息,因此您应该能够为该路径定义路径并在应用中处理它。 请记住,这不会发生在开发模式中,因此您需要在其他环境中尝试它。 如果在生产中没有发生这种情况,请尝试将omniauth gem升级到1.1.0版
我用法比奥的第一个建议解决了这个问题。
OmniAuth.config.on_failure = Proc.new do |env|
UsersController.action(:omniauth_failure).call(env)
#this will invoke the omniauth_failure action in UsersController.
end
在我的UsersController中
class UsersController < ActionController::Base
def omniauth_failure
redirect_to init_sign_in_users_path
#redirect wherever you want.
end
end
有一个配置使用/auth/failure
而不是引发错误。
我用OmniAuth 1.2.2,当我检查FailureEndpoint我发现的代码是像这样 :
def call
raise_out! if OmniAuth.config.failure_raise_out_environments.include?(ENV['RACK_ENV'].to_s)
redirect_to_failure
end
而failure_raise_out_environments
在这里定义:
def self.defaults
@defaults ||= {
# other configurations
:failure_raise_out_environments => ['development']
}
end
可以配置环境以便解决方案。 我使用Rails,所以我将下面的代码放在初始化文件中:
OmniAuth.configure do |config|
# Always use /auth/failure in any environment
config.failure_raise_out_environments = []
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.