2011-11-01 33 views
6

Tôi muốn triển khai xác thực cơ sở HTTP trên máy chủ dàn dựng của mình, nhưng chỉ cho những người bên ngoài mạng cục bộ. Tôi có một ứng dụng Rails 3.1. Trong application.rb, tôi có như sau:Xác thực HTTP có điều kiện cơ bản

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 

Đây là chà: ngay cả khi các phương pháp need_authentication?rõ ràng lợi nhuận false, ứng dụng vẫn hỏi tôi để xác thực, như thể nó hoàn toàn phớt lờ các mệnh đề if cuối cùng.

Vì vậy, có cách nào để chỉ yêu cầu xác thực trong các điều kiện nhất định không?

Trả lời

6

Đây là những gì làm việc:

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' là tên của vương quốc. Điều này là không cần thiết, nhưng có thể được sử dụng để làm rõ.

-3

Hãy thử điều này:

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' là một phương pháp học. Tôi đã thử đặt nó vào trong một phương thức khác, như bạn đã mô tả ở trên, nhưng điều đó mang lại cho tôi một ngoại lệ 'undefined method'. – partydrone

7

Trong Rails 4, điều kiện: nếu hoạt động. Ví dụ,

class ApplicationController < ApplicationController::Base 
    http_basic_authenticate_with name: "user", password: "password" if Rails.env == 'staging' 
end 

hoặc nếu bạn muốn có một phương pháp helper để đặt điều kiện,

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

    private 
    def need_authentication? 
    Rails.env == 'staging' 
    end 
end 
Các vấn đề liên quan