由于重定向,设计JSON API返回406而不是401

时间:2013-02-27 02:45:35

标签: ruby-on-rails-3 api authentication devise warden

我尝试在没有正确身份验证的情况下尝试请求端点时尝试返回401和错误消息。

目前正是这样:

开始GET" /api/v1/home/index.json"对于127.0.0.1在2013-02-27 02:40:22 +0000 由HomeController处理#index为JSON 在0ms完成401 Unauthorized

开始GET" /api/v1/sign_in.json"对于127.0.0.1在2013-02-27 02:40:22 +0000 由SessionsController处理#new作为JSON 完成406在1ms内不可接受(ActiveRecord:0.0ms)

我怎样才能阻止设计将我弹回sign_in,而是让它只返回401 / json响应。

我认为这可能与我尝试过的CustomFailureApp有关,但我不确定在这种特定情况下是否调用了CustomFailureApp。

1 个答案:

答案 0 :(得分:1)

您可以制作自定义失败应用。

class JsonFailureApp < Devise::FailureApp
  def respond
    self.status = 401
    self.content_type = 'json'
    self.response_body = '{"error" : "Authentication error"}'
  end
end

将此添加到您的设计初始化程序

config.warden do |manager|
  manager.failure_app = JsonFailureApp
end
相关问题