2012-04-06 52 views
19

我使用设计的authenticate_user!方法在控制器中。这是工作正常,当请求中提供的AUTH_TOKEN是正确的,但如果验证失败,我结束了:如何在设计中删除html重定向authenticate_user

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> 

,因为我用Rabl的,什么是有一些像

的最佳方式
{'error' : 'authentication error'} 

返回intead的html重定向?

回答

41

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

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 

的另一种方式,可以清洁是定义自己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 

在你设计的配置文件中加入:

config.warden do |manager| 
    manager.failure_app = MyFailureApp 
end 
+0

我试过第二种方法,以避免不必在我的所有控制器中重复相同的代码。我创建了MyFailureApp类到lib/failure.rb并更改配置。我没有设法让它工作,但我得到'!!处理请求时出现意外错误:未初始化的常量MyFailureApp'。任何想法为什么这个人没有被装载? – Luc 2012-04-06 10:31:27

+0

你需要你的文件需要'失败'在设计配置顶部 – shingara 2012-04-06 11:39:18

+0

(愚蠢的我)很好,这工作正常。谢谢。 – Luc 2012-04-06 12:00:31

32

在设计的新版本(我使用2.2.0),你可以使用在设计配置文件中的navigational_formats选项,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] 

只要:json不在该列表中,您的要求结束于.json,它将按照你的意愿行事。

+2

这节省了我不可思议的时间,谢谢! – 2014-04-06 04:37:25

+0

我一整天都很困惑,直到我看到你对以.json结尾的请求的观点。好表演,好表演。 – 2014-07-17 20:53:43

+2

将'application/json'添加到请求的Headers中,并且在url结尾不需要'.json'。 – rmagnum2002 2015-06-21 14:56:59