我想在登台服务器上实现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子句一样.
那么,有没有办法只在某些条件下要求身份验证?
我无法使用minitest在我的Rails 4.2应用程序中成功测试自定义HTTP变量 - 出于某种原因,Rails似乎根本不识别它们.
我有以下测试:
require "test_helper"
describe ApplicationController do
tests HomeController
before do
cookies[:locale] = "ru"
request.headers["Accept-Language"] = "zh-cn, en-us"
request.headers["CloudFront-Viewer-Country"] = "FR"
I18n.default_locale = :en
end
it "sets locale from URL params first" do
get :index, locale: "de"
I18n.locale.must_equal :de
end
it "sets locale from a cookie second" do
get :index
I18n.locale.must_equal :ru
end
it "sets locale from Accept-Language header third" do
cookies.delete :locale
get :index
I18n.locale.must_equal :"zh-CN"
end
it "sets locale from CloudFront-Viewer-Country header last" do
cookies.delete …Run Code Online (Sandbox Code Playgroud)