条件HTTP基本身份验证

6

我希望在我的演示服务器上实现HTTP基本认证,但仅限于本地网络之外的用户。我的应用程序是Rails 3.1。在application.rb中,我有以下内容:

class ApplicationController << ActionController::Base
  http_basic_authenticate_with :realm => "Staging", :name => "user", :password => "password" if :need_authentication?

private

  def need_authentication?
    Rails.env == "staging" && request.remote_addr !~ /^192.168.0.\d{1,3}$/
  end

end

这里的问题在于,即使need_authentication?方法明确返回false,应用程序仍然要求我进行身份验证,就好像它完全忽略了结尾处的if子句。
那么,有没有办法只在特定条件下需要身份验证呢?
2个回答

7
在Rails 4中,:if条件可以正常工作。例如,
class ApplicationController < ApplicationController::Base
  http_basic_authenticate_with name: "user", password: "password" if Rails.env == 'staging'
end

或者,如果您想要一个设置条件的帮助方法,
class ApplicationController < ApplicationController::Base
  http_basic_authenticate_with name: "user", password: "password", if: :need_authentication?

  private
  def need_authentication?
    Rails.env == 'staging'
  end
end

6
这是有效的方法:

这是有效的方法:

class ApplicationController < ActionController::Base
  before_filter :authenticate_if_staging

private

  def authenticate_if_staging
    if Rails.env == 'staging' && request.remote_addr !~ /^192.168.0.\d{1,3}$/
      authenticate_or_request_with_http_basic 'Staging' do |name, password|
        name == 'username' && password == 'secret'
      end
    end
  end
end

'Staging'是指环境的名称。这不是必需的,但可以用于澄清。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接