【问题标题】:Custom handler for Rails 401 authentication errorsRails 401 身份验证错误的自定义处理程序
【发布时间】:2013-12-24 04:52:32
【问题描述】:

我有一个 API 控制器,重要的是所有错误响应都以 JSON 格式返回。

以下设置处理操作引发的错误,但不处理 before 过滤器中引发的身份验证错误 - 它会抛出一个 401,rails 作为 text/html 发送出去。

  class ApiController < ActionController::Base

    rescue_from StandardError, with: :handle_errors
    before_filter :restrict_access

    def restrict_access
      authenticate_or_request_with_http_token do |token, options|
        false # Force authentication error
      end
    end

    def handle_errors(exception)
      render :json => { :errors => { :error => exception.message} }.to_json, :status => 400
    end

我需要做什么来处理身份验证错误?

【问题讨论】:

    标签: ruby-on-rails error-handling


    【解决方案1】:

    在@Gjaldon 的回答帮助我弄清楚之后,我最终在我的 API 控制器中覆盖了 request_http_token_authentication:

    def request_http_token_authentication(realm = "Application")  
      self.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
      self.__send__ :render, :json => { :error => "HTTP Token: Access denied. You did not provide an valid API key." }.to_json, :status => :unauthorized
    end
    

    【讨论】:

    • 讨厌这样做,但想不出更聪明的方法。
    【解决方案2】:

    当访问被拒绝时,下面的方法被调用。

    def Token.authentication_request(controller, realm)
      controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
      controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
    end
    

    您可以尝试覆盖它以更改以下行为:

    def Token.authentication_request(controller, realm)
      controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
      controller.__send__ :render, :json => { :errors => { :error => exception.message} }.to_json, :status => 400
    end
    

    【讨论】:

    • @Gjaldon- 谢谢,这让我到了那里,尽管我发现覆盖 request_http_token_authentication 控制器方法而不是猴子修补更容易 - 请参阅my answer。
    • 那么酷!我很高兴我的回答有帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2020-07-23
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2020-01-07
    相关资源
    最近更新 更多