ruby-on-rails - 通过 json 设计失败身份验证发回 html 而不是 json

标签 ruby-on-rails json devise

我已经成功设置了 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/

相关文章:

ruby-on-rails - Rails 设计删除寄存器

长数字的 JSON 解码给出 float

ruby-on-rails - Devise 和 devise_cas_authenticable 出现 PG::UniqueViolation 错误

ios - 如何检查 objective-c 中的 JSON 格式?

ruby-on-rails - 使用 Devise 和 OmniAuth-SAML 在 Rails 中设置 SAML 回调

mysql - Rails 4 设计具有随 secret 码的种子用户

javascript - 如何在ajax重定向中传递创建表单生成器

ruby-on-rails - Gem unf_ext 未能构建 gem native 扩展

ruby-on-rails - 向 rails aasm 状态添加验证

javascript - Polymer JS POST JSON 格式