通过json的Devise失败认证发回html而不是json [英] Devise failure authentication via json sends back html instead of json
问题描述
class Users :: SessionsController< Devise :: SessionsController
def create
respond_to do | format |
format.html {super}
format.json {
warden.authenticate!(:scope => resource_name,:recall =>#{controller_path} #failure)
render:json => {:success => true}
}
end
end
def destroy
respond_to do | format |
format.html {super}
format.json {
Devise.sign_out_all_scopes? sign_out:sign_out(resource_name)
render:json => {}
}
end
end
def failure
render:json => {:success => false,:errors => [登录失败]}
结束
结束
但是当身份验证失败时,失败不会返回json失败。我有一个自定义失败的设计。如果我删除redirect_url或完全删除客户故障,则验证将返回一个具有失败消息的json。我的自定义失败如下:
class CustomFailure< Devise :: FailureApp
def redirect_url
#return super除非[:worker,:雇主,用户] .include?(scope)#make具体到范围
'/'
end
#你需要覆盖响应以消除召回
def response
如果http_auth?
http_auth
else
重定向
结束
结束
end
无论如何保持重定向,如果它的一个html请求,并返回一个json与失败msg如果它的一个json请求?
谢谢!
您必须告诉监护人才能使用该自定义失败。 p>
def failure
respond_to do | format |
format.html {super}
format.json do
warden.custom_failure!
render:json => {:success => false,:errors => [登录失败]}
结束
结束
结束
I have managed to setup json authentication. I implemented the following code:
class Users:: SessionsController < Devise::SessionsController
def create
respond_to do |format|
format.html { super }
format.json {
warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
render :json => {:success => true}
}
end
end
def destroy
respond_to do |format|
format.html {super}
format.json {
Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
render :json => {}
}
end
end
def failure
render :json => {:success => false, :errors => ["Login Failed"]}
end
end
This works fine, but when authentication fails, the failure doesnt return the json failure. I have a custom failure for devise. If I remove the redirect_url or remove the customer failure completely, then the authentication returns a json with the failure message. My custom failure is as follows:
class CustomFailure < Devise::FailureApp
def redirect_url
#return super unless [:worker, :employer, :user].include?(scope) #make it specific to a scope
'/'
end
# You need to override respond to eliminate recall
def respond
if http_auth?
http_auth
else
redirect
end
end
end
Anyway to keep the redirect if its an html request, and return a json with a failure msg if its a json request?
Thanks!
You have to tell warden to use that custom failure.
def failure
respond_to do |format|
format.html {super}
format.json do
warden.custom_failure!
render :json => {:success => false, :errors => ["Login Failed"]}
end
end
end
这篇关于通过json的Devise失败认证发回html而不是json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!