我已经成功设置了 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 => ["Login Failed"]}
end
end
这工作正常,但是当身份验证失败时,失败不会返回 json 失败。我有一个自定义的设计失败。如果我删除 redirect_url 或完全删除客户失败,则身份验证将返回一个带有失败消息的 json。我的自定义失败如下:
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
结尾
无论如何要保持重定向,如果它是一个 html 请求,并返回一个带有失败 msg 的 json 如果它是一个 json 请求?
谢谢!
最佳答案
您必须告诉管理员使用该自定义失败。
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
关于ruby-on-rails - 通过 json 设计失败身份验证发回 html 而不是 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11277300/