我使用了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>
当我使用rabl时,最好的方法是使用
{'error' : 'authentication error'}
返回了html重定向的intead?
答案 0 :(得分:43)
我这样做是为了避免过滤器:format =&gt; :如果没有current_user传递
,json响应并执行我自己的过滤器来呈现我的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
另一种方法,更清晰的是定义自己的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
答案 1 :(得分:35)
在较新版本的Devise(我使用的是2.2.0)中,您可以使用Devise配置文件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
结尾,它就会按照您的意愿行事。