Ruby on rails 使用Desive针对身份验证失败的自定义XML响应
我正在使用XML POST登录我的用户,如果身份验证不起作用,我需要返回一个XML响应。然而,XML响应的格式需要定制,我不能告诉Desive我应该在哪里更改这个输出 在“user\u sessions\u controller.rb”的“create”方法中,我有一个普通调用:Ruby on rails 使用Desive针对身份验证失败的自定义XML响应,ruby-on-rails,ruby,xml,devise,Ruby On Rails,Ruby,Xml,Devise,我正在使用XML POST登录我的用户,如果身份验证不起作用,我需要返回一个XML响应。然而,XML响应的格式需要定制,我不能告诉Desive我应该在哪里更改这个输出 在“user\u sessions\u controller.rb”的“create”方法中,我有一个普通调用: def create resource = warden.authenticate!(:scope => resource_name, :
def create
resource = warden.authenticate!(:scope => resource_name,
:recall => "#{controller_path}#new")
这是返回的:
<errors>
<error>Invalid email or password.</error>
</errors>
无效的电子邮件或密码。
但我需要在这上面加一个包装:
<AppName>
<errors>
<error>Invalid email or password.</error>
</errors>
</AppName>
无效的电子邮件或密码。
您可以在自定义故障应用程序中重新定义http\u auth\u body
方法:
# lib/custom_failure_app.rb
class CustomFailure < Devise::FailureApp
protected
def http_auth_body
return i18n_message unless request_format
method = "to_#{request_format}"
if method == "to_xml"
{ :errors => { :error => i18n_message } }.to_xml(:root => Rails.application.class.parent_name)
elsif {}.respond_to?(method)
{ :error => i18n_message }.send(method)
else
i18n_message
end
end
end
并将其添加到application.rb
:
config.warden do |manager|
manager.failure_app = CustomFailure
end
config.autoload_paths += %W(#{config.root}/lib)
结果:
curl -X POST http://localhost:3000/users/sign_in.xml -d "{}"
<?xml version="1.0" encoding="UTF-8"?>
<DeviseCustom>
<errors>
<error>You need to sign in or sign up before continuing.</error>
</errors>
</DeviseCustom>
curl-X POSThttp://localhost:3000/users/sign_in.xml -d“{}”
继续之前,您需要登录或注册。