Custom Devise 401未经授权的响应

Mat*_*ins 19 authorization ruby-on-rails unauthorized devise ruby-on-rails-3

我正在为我的Rails 3.1应用程序开发基于JSON的API.我想提供自定义失败响应而不是默认响应,即:

{"error":"You need to sign in or sign up before continuing."}
Run Code Online (Sandbox Code Playgroud)

我的API控制器包含一个before_filter调用authenticate_user!,它正在呈现此JSON响应.

在搜索时,我遇到了这个StackOverflow问题,该问题引用了这个Devise wiki条目.不幸的是,wiki条目并不足以让我理解它告诉我的内容.具体来说,我不知道我应该把那些代码放在哪里,以便Devise/Warden知道要渲染我想要的东西.

从其他SA问题的评论来看,听起来我不需要打电话,custom_failure!因为我使用的是高于1.2的Devise版本(具体为1.4.2).但是,wiki条目没有解释render调用应该去哪里,以便authenticate_user!知道使用它而不是自己的render调用.

这个render电话在哪里?

编辑:我不只是试图改变消息本身(一个设计en.yml配置); 我正在尝试更改响应的实际格式.具体来说,我想返回这个:

render :text => "You must be logged in to do that.", :status => :unauthorized
Run Code Online (Sandbox Code Playgroud)

qix*_*qix 23

如果在使用Devise进行失败的登录尝试时寻找如何自定义json错误响应时,其他人偶然发现这个问题的参考,关键是使用您自己的自定义FailureApp实现.(您也可以使用此方法覆盖某些重定向行为.)

class CustomFailureApp < Devise::FailureApp
  def respond
    if request.format == :json
      json_error_response
    else
      super
    end
  end

  def json_error_response
    self.status = 401
    self.content_type = "application/json"
    self.response_body = [ { message: i18n_message } ].to_json
  end
end
Run Code Online (Sandbox Code Playgroud)

并在你的devise.rb,寻找config.warden部分:

  config.warden do |manager|
    manager.failure_app = CustomFailureApp
  end
Run Code Online (Sandbox Code Playgroud)

一些相关信息:

起初我还以为我将不得不重写设计:: SessionsController,可能使用recall传递给选项warden.authenticate!,但提到这里,"召回不能调用的API请求,只为导航的.如果你想自定义HTTP状态代码,在失败的应用程序级别,你会有更好的运气."

另外https://github.com/plataformatec/devise/wiki/How-To%3a-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated显示了一些非常类似的重定向.