如何在设计authenticate_user中删除html重定向

我使用devise的authenticate_user! 控制器中的方法。 当请求中提供的auth_token是正确的时,这工作正常,但如果身份validation失败,我最终得到:

curl -XGET 'http://localhost:3000/my_obj?auth_token=wrongtoken' You are being redirected. 

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

 {'error' : 'authentication error'} 

返回html重定向的intead?

我这样做是为了避免filter:format =>:json response并做我自己的filter来呈现我的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 

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

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

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

 # ==> 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结尾,它将按您的意愿运行。

Interesting Posts