Rails设计/令牌认证:如果令牌错误或丢失则重定向

时间:2013-03-13 09:36:21

标签: ruby-on-rails redirect devise token

我使用令牌认证/ json api实现了Devise。 我现在的问题是,每当“?auth_token”错误或丢失时,设计会将“HTTP / 1.1 302暂时移动”重定向到我想要的json错误响应,而不是直接将其返回:“HTTP / 1.1 403 Forbidden”。

我的错误响应来自我的SessionsController<设计:: SessionsControllers“新”动作,我认为它可能是错误的地方。

我无法找到设计重定向的位置或我可以更改此行为的位置。任何人都可以给我一个线索吗?

非常感谢, 克里斯

2 个答案:

答案 0 :(得分:4)

您可以创建一个自定义失败 ruby​​文件,并根据需要提供重定向,方法是将其放在lib目录中,然后将其包含在您的设计initializer中,如此处所述{ {3}}

失败应用的定义定义如下:

SO Post

OR

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

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不正确,则意味着没有用户应该登录该应用程序,因此您可以显示authentication error 403

答案 1 :(得分:3)

仅出于文档目的,这里是我执行的步骤:

HOWTO devise custom failure app

添加到 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
相关问题