【问题标题】:Custom XML response for auth failure using Devise使用设计的身份验证失败的自定义 XML 响应
【发布时间】:2012-01-02 00:53:39
【问题描述】:

我正在使用 XML POST 登录我的用户,如果身份验证不起作用,我需要返回 XML 响应。但是,XML 响应的格式需要自定义,我不知道应该在 Devise 的哪个位置更改此输出。

在“user_sessions_controller.rb”的“创建”方法中,我有普通调用:

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>

【问题讨论】:

    标签: ruby-on-rails ruby xml devise


    【解决方案1】:

    您可以在自定义故障应用中重新定义http_auth_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
    

    然后将其添加到initializers/devise.rb:

    config.warden do |manager|
      manager.failure_app = CustomFailure
    end
    

    并将其添加到application.rb:

    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>
    

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 2017-08-07
      • 2020-10-29
      • 2012-01-29
      • 2022-08-10
      • 1970-01-01
      • 2023-03-19
      • 2020-02-17
      • 2020-08-28
      相关资源
      最近更新 更多