Conditional HTTP Authentication

I want to implement basic HTTP authentication on my intermediate server, but only for those who are outside the local network. I have a Rails 3.1 application. In application.rb, I have the following:

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 

Here rub: even when the need_authentication? method need_authentication? explicitly returns false , the application still asks me for authentication, as if it completely ignores the if clause at the end.

So, is there a way to require authentication under certain conditions?

+6
source share
3 answers

This is what worked:

 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' is the name of the area. This is not required, but can be used for clarification.

+6
source

In Rails 4, the condition is: if. For instance,

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

or if you want the helper method to set a condition,

 class ApplicationController < ApplicationController::Base http_basic_authenticate_with name: "user", password: "password", if: :need_authentication? private def need_authentication? Rails.env == 'staging' end end 
+7
source

Try the following:

 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 
-3
source

Source: https://habr.com/ru/post/900564/


All Articles