authenticate_or_request_with_http_basic始终返回false

时间:2014-05-09 13:14:01

标签: ruby-on-rails ruby-on-rails-2 http-basic-authentication

在我的Rails 2.3应用程序中,我们有一个受基本HTTP身份验证保护的管理部分。多年来,这一直在我们的生产和登台环境中发挥作用。最近我设置了一个新环境来演示一个长期运行的功能分支,并区分它和其他临时服务器,我将其设置为使用自定义"重新设计"环境。所以现在我的Admin::BaseController看起来像这样:

class Admin::BaseController < ApplicationController
  before_filter :verify_access

  def verify_access
    logger.info "\n\n-- running verify_access filter on #{RAILS_ENV}\n"
    if %w(production staging redesign).include?(RAILS_ENV)
      logger.info "\n-- should send authentication\n"
      authenticate_or_request_with_http_basic("Restricted Access") do |username, password|
        logger.info "\nauthentication received: {username}::#{password}\n"
        username == 'myusername'
        password == 'mypassword' 
      end 
    end
  end
end

出于某种原因,新服务器总是响应未授权并且不提供任何登录对话框,即使我退出并重新打开浏览器也没有,即使我使用私人浏览器会话,即使我指定了URL中的用户名(即http://username@www.mysite.com/admin)。它只是自动将我重定向到根并将?unauthorized=true添加到查询字符串中,尽管在我的应用程序代码中没有任何地方可以做到这一点。

我知道它正在点击verify_access过滤器,因为我可以在日志文件中看到它:

Processing Admin::OrdersController#index (for xx.xx.xx.xx at 2014-05-09 05:56:59) [GET]
  Parameters: {"action"=>"index", "controller"=>"admin/orders"}

-- running verify_access filter on redesign

-- should send authentication

Filter chain halted as [:verify_access] rendered_or_redirected.
Completed in 25ms (View: 21, DB: 1) | 401 Unauthorized [http://www.mydomain.com/admin/orders]


Processing IndexController#show (for xx.xx.xx.xx at 2014-05-09 05:56:59) [GET]
  Parameters: {"action"=>"show", "controller"=>"index", "unauthenticated"=>"true"}
Rendering index/show
Completed in 30ms (View: 27, DB: 3) | 200 OK [http://www.mydomain.com/?unauthenticated=true]

在Chrome的网络面板中,管理页面的请求实际上显示它正在从服务器接收302 Found响应,即使Rails发送的是401 Unauthorized。

GET /admin/orders HTTP/1.1
Host: www.mydomain.com
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: _myapp_session=xxx

HTTP/1.1 302 Found
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive
Status: 302
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 2.2.10
Location: /?unauthenticated=true
Server: nginx/0.7.65 + Phusion Passenger 2.2.10 (mod_rails/mod_rack)

新服务器是原始登台服务器的克隆,因此架构完全相同,并且使用了所有相同的主厨配方。关于这里发生了什么的任何想法?

1 个答案:

答案 0 :(得分:0)

原来的HTTP Basic Auth正在绊倒Devise,这是该分支的新功能之一。将我的verify_access方法更新为以下解决了问题:

def verify_access
  if %w(production staging redesign).include?(RAILS_ENV)
    authenticate_or_request_with_http_basic("Restricted Access") do |username, password|
      username == 'username' && password == 'password'
    end
  end
  warden.custom_failure! if performed?
end