条件HTTP基本身份验证

par*_*one 6 ruby-on-rails basic-authentication

我想在登台服务器上实现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
Run Code Online (Sandbox Code Playgroud)

这就是问题:即使need_authentication?方法明确返回false,应用程序仍然要求我进行身份验证,就好像它完全忽略了最后的if子句一样.

那么,有没有办法只在某些条件下要求身份验证?

Din*_*gle 7

在Rails 4中,:if条件有效.例如,

class ApplicationController < ApplicationController::Base
  http_basic_authenticate_with name: "user", password: "password" if Rails.env == 'staging'
end
Run Code Online (Sandbox Code Playgroud)

或者如果你想要一个辅助方法来设置条件,

class ApplicationController < ApplicationController::Base
  http_basic_authenticate_with name: "user", password: "password", if: :need_authentication?

  private
  def need_authentication?
    Rails.env == 'staging'
  end
end
Run Code Online (Sandbox Code Playgroud)


par*_*one 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
Run Code Online (Sandbox Code Playgroud)

'Staging'是领域的名称.这不是必需的,但可用于澄清.