Rails Devise/Token认证:如果令牌无效或缺失,则重定向。

3
我已经使用token身份验证/json api实现了Devise。我的问题是,每当"?auth_token"错误或缺失时,Devise会将我重定向到我的预期json错误响应,而不是直接返回它:"HTTP/1.1 403 Forbidden"。
我的错误响应来自我的SessionsController < Devise :: SessionsControllers "new"操作,我认为这可能是错误的位置。
我找不到Devise执行重定向的地方或者我可以更改此行为的地方。是否有人可以给我一些提示?
非常感谢, 克里斯
2个回答

4
你可以创建一个自定义失败的 Ruby 文件,通过将其放置在 lib 目录中并在 Devise 的 initializer 中包含它,按照你想要的方式提供重定向。具体实现方法可以参考这个 SO Post
失败应用程序的定义在以下位置:

https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb

或者

您可以在自己的控制器中使用以下代码:

before_filter :correct_auth, :if => { request.format == :json }

  def correct_auth
    unless current_user
      render :json => {'error' => 'authentication error'}, :status => 403
    end
  end

如果您的auth_token不正确,那么没有用户应该登录到应用程序中,因此您可以显示身份验证错误403

谢谢您的回复。 我刚刚尝试了您的第二种方法,但我仍然得到了重定向作为响应。如果我跟随重定向,我会被带到正确的消息。然而,我想要摆脱这个重定向。我将尝试您的第一种方法。我记得我已经尝试过创建自定义失败,并且也遇到了一些麻烦。 - chris h.
第一种方法奏效了!谢谢。我现在发现,我发送请求的http客户端显示“((从服务器返回零长度响应。))”而不是401未经授权...所以我认为我的实现有问题。 - chris h.

3

仅供文档记录,这里是我执行的步骤:

如何使用devise自定义失败应用程序

添加到devise.rb

  config.warden do |manager|
    manager.failure_app = CustomFailure
  end

创建 lib/devise/custom_failure.rb 文件。
class CustomFailure < Devise::FailureApp

  def redirect_url
    login_page_url
  end

  # You need to override respond to eliminate recall
  def respond
    if http_auth?
      http_auth
    else
      if request.format.json?
        self.status = :unauthorized
        self.response_body = { :elements => {:id => "Authentication Failed", :description =>   "Invalid or missing authentication token"} }.to_json
        self.content_type = "json"
      else
        redirect
      end
    end
  end

end

非常有帮助!感谢解决方案。 - James Hamilton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接