2011-11-01 114 views
6

我想在暫存服務器上實現HTTP基本認證,但僅限於本地網絡以外的用戶。我有一個Rails 3.1應用程序。在application.rb中,我有以下幾點:有條件的HTTP基本認證

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,應用仍然問我來驗證,因爲如果它完全無視如果條款最後。

那麼,有什麼辦法只需要在某些條件下認證?

回答

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 

'分期' 是域的名稱。這不是必需的,但可用於澄清。

-3

試試這個:

class ApplicationController < ActionController::Base 
    before_filter :do_auth 

    def do_auth 
    http_basic_authenticate_with :realm => "Staging", :name => "user", :password => "password" if :need_authentication? 
    end 

private 

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

end 
+1

'http_basic_authenticate_with'是一個類的方法。我試着把它放在另一個方法中,就像你上面描述的那樣,但是這給了我一個'未定義的方法'異常。 – partydrone

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