如何在设计authenticate_user中删除html重定向 [英] How to remove html redirection in devise authenticate_user
问题描述
我使用设备的authenticate_user!控制器中的方法.当请求中提供的 auth_token 正确时,这工作正常,但如果身份验证失败,我会得到:
I use the devise's authenticate_user! method in a controller. This is working fine when the auth_token provided in the request is the correct one but if the authentication fails, I end up with:
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 时,最好的方法是什么
As I use rabl, what is the best way to have something like
{'error' : 'authentication error'}
返回的不是 html 重定向?
returned intead of the html redirection ?
推荐答案
我这样做是为了避免使用 :format => :json 响应的过滤器,并在没有 current_user 时使用我自己的过滤器来呈现我的 JSON 响应
I do that in avoid the filter with :format => :json response and do my own filter to render my JSON response if no current_user pass
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 )
An other way, can be cleaner is to define your own 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
在你的设计配置文件中添加:
In your Devise config file add :
config.warden do |manager|
manager.failure_app = MyFailureApp
end
这篇关于如何在设计authenticate_user中删除html重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!