繁体   English   中英

Rails 2.x通过HTTP基本身份验证提供有意义的错误消息

[英]Rails 2.x provide meaningful error message with http basic authentication

我通过以下代码在Rails应用程序中使用基本的HTTP身份验证:

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  before_filter :authenticate

private
  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      if username.nil? || password.nil?
        render :inline => %(xml.instruct! :xml, :version => "1.0", :encoding => "UTF-8"
                            xml.errors do
                              xml.error('Could not authenticate you.')
                            end), :type => :builder, :status => 401
      end
    end
  end
end

问题是,如果在不提供-u username:password标志的情况下进行curl http://127.0.0.1:3000/foo/1.xmlcurl http://127.0.0.1:3000/foo/1.xml ,则会得到如下所示的死跳响应:

HTTP/1.1 401 Unauthorized 
Cache-Control: no-cache
WWW-Authenticate: Basic realm="Foo"
X-Runtime: 1
Content-Type: text/html; charset=utf-8
Content-Length: 27
Server: WEBrick/1.3.1 (Ruby/1.9.1/2010-01-10)
Date: Thu, 03 Jun 2010 03:09:18 GMT
Connection: Keep-Alive

HTTP Basic: Access denied.

如果用户未提供用户名和密码,是否可以渲染上面的内联XML?

这可能不是最安全的方法,但是您可以尝试一下。

首先,继续构建自定义错误:

#construct a custom error class
class AuthenticationError < StandardError
  # error code goes here
end

现在在您的代码块中引发该错误:

xml.errors do
  raise AuthenticationError
end

您现在可以使用ActionController的rescue_from方法来处理自定义错误消息:

class ApplicationController < ActionController::Base
  rescue_from AuthenticationError { |e| xml_status_error(:unauthorized, e) }

  def xml_status_error(status,exception)
    respond_to do |format|
      format.xml { #here you go! }
      format.any { head status } #just return the status code
    end
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM