2011-11-01 122 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