如何在devise authenticate_user中删除html重定向

Luc*_*Luc 22 ruby-on-rails devise ruby-on-rails-3 rabl

我使用devise的authenticate_user!控制器中的方法.当请求中提供的auth_token是正确的,但如果身份验证失败,我最终得到的结果是:

curl -XGET 'http://localhost:3000/my_obj?auth_token=wrongtoken'

<html><body>You are being <a href="http://localhost:3000/users/sign_in">redirected</a>.</body></html>
Run Code Online (Sandbox Code Playgroud)

当我使用rabl时,有什么是最好的方法

{'error' : 'authentication error'}
Run Code Online (Sandbox Code Playgroud)

返回html重定向的intead?

shi*_*ara 43

我这样做,在避免与过滤器:格式=>:JSON响应,做自己的过滤器来呈现,如果没有CURRENT_USER通我的JSON响应

class MyController < ApplicationController
  before_filter :authenticate_user!, :unless => { request.format == :json }
  before_filter :user_needed, :if => { request.format == :json }

  def user_needed
    unless current_user
      render :json => {'error' => 'authentication error'}, :status => 401
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

另一种方式,更清晰的是定义自己的FailureApp(https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb)

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

  def json_failure
    self.status = 401
    self.content_type = 'application/json'
    self.response_body = "{'error' : 'authentication error'}"
  end
end
Run Code Online (Sandbox Code Playgroud)

在您的Devise配置文件中添加:

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

  • @shingara` ==:json`在`if request.format ==:json`(`respond`方法)中缺失,不是吗?否则,`json_failure`也将以其他格式呈现,例如HTML. (2认同)

law*_*nce 36

在较新版本的Devise(我使用的是2.2.0)中,您可以使用navigational_formatsDevise配置文件中的选项devise.rb:

# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
config.navigational_formats = ["*/*", :html]
Run Code Online (Sandbox Code Playgroud)

只要:json不在该列表中,并且您的请求结束.json,它将按您的意愿运行.

  • 将`application/json`添加到请求的`Headers`中,你不需要在URL的末尾添加`.json`. (4认同)
  • 这给我节省了不可思议的时间,谢谢! (2认同)