如何解救OmniAuth :: Strategies :: OAuth2 :: CallbackError?

Sou*_*amy 40 ruby-on-rails callback oauth-2.0 omniauth ruby-on-rails-3

我正在使用Omniauth构建Rails应用程序以进行登录服务.要对Google进行身份验证,我使用的是OmniAuth Google OAuth2策略.

当用户点击"允许访问"按钮时,一切正常.但是当用户点击"不再感谢"按钮时,会出现以下错误.

OmniAuth::Strategies::OAuth2::CallbackError
Run Code Online (Sandbox Code Playgroud)

我尝试在应用程序控制器中添加以下救援代码.

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
Run Code Online (Sandbox Code Playgroud)

但没有运气.

任何的想法?

谢谢 :)

Pet*_* P. 64

您可以以更清晰的方式在omniauth初始化程序中设置on_failure proc:

OmniAuth.config.on_failure = UsersController.action(:oauth_failure)
Run Code Online (Sandbox Code Playgroud)

  • 此代码在生产环境中运行良好.但是,如果在开发环境中更改UsersController#oauth_failure代码,则不会看到任何更改.基于Proc的声纳代码在开发中更好,并且在开发过程中按预期工作. (3认同)
  • Rails 6 上的此代码将导致弃用警告,因为控制器将在初始化过程中进行初始化。此版本避免了此问题:/sf/answers/752033901/ (2认同)

Fab*_*bio 36

发生这种情况是因为身份验证发生在中间件中,因此您的控制器不会参与其中.这是引发异常的地方,被调用的代码就是这个

我认为你可以通过使用这种代码在Omniauth初始化程序中定义回调来处理这种错误

Omniauth.config do |config|
  config.on_failure do
    # your handling code invoked in the context of a rack app
  end
end
Run Code Online (Sandbox Code Playgroud)

否则会有三个月前的提交引入此行为

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
Run Code Online (Sandbox Code Playgroud)

这表明错误会导致用户重定向到/auth/failure错误消息,因此您应该能够为该路径定义路径并在应用中处理它.请记住,这不会在开发模式中发生,因此您需要在其他环境中尝试它.如果在生产中没有发生这种情况,请尝试将omniauth gem升级到1.1.0版

  • 1000.times.do把"非常感谢!" 结束 (16认同)
  • 我使用`OmniAuth`而不是'Omniauth`工作.看起来大写已经改变了. (2认同)
  • 要在开发模式下测试失败,可以添加以下内容:`OmniAuth.config.failure_raise_out_environments = [] (2认同)

Sou*_*amy 17

我用法比奥的第一个建议解决了这个问题.

OmniAuth.config.on_failure = Proc.new do |env|
  UsersController.action(:omniauth_failure).call(env)
  #this will invoke the omniauth_failure action in UsersController.
end
Run Code Online (Sandbox Code Playgroud)

在我的UsersController中

class UsersController < ActionController::Base
  def omniauth_failure
    redirect_to init_sign_in_users_path
    #redirect wherever you want.
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 在哪里我必须把上面的代码Omniauth.config.on_failure = Proc.new do | env | "UsersController".constantize.action(:omniauth_failure).call(env)#this将调用UsersController中的omniauth_failure操作.结束 (4认同)
  • 将代码放在config/initializers/omniauth_failure_callback.rb文件中.我建议你使用彼得的代码,因为它非常干净. (2认同)
  • @soundar,虽然彼得的代码更清晰,但您的代码在开发环境中按照预期在开发环境中工作.所以你的答案也是+1. (2认同)