DEV Community

@kon_yu
@kon_yu

Posted on

How to do not apply basic authentication to certain URLs in a Rails project with basic authentication method

If you can write basic authentication in a staging environment or other environment, you can use the configuration file
For example, the following in the config/environment/production.rb

if ENV["STAGING"] #set environmental variable
  config.middleware.use Rack::Auth::Basic do |username, password|
    username == "YOUR_NAME" && password == "PASSWORD"
  end
end
Enter fullscreen mode Exit fullscreen mode

Now, if you want to access certain URLs without using basic authentication, you need to extend Rack::Basic Auth::Basic to access certain URLs without using basic authentication.

There are several ways to write it, but the following conditions should be met

  • Only enable in the staging environment.
  • Do not apply basic authentication to certain URLs that match a regular expression.
  • Put the extended class files under the lib directory instead of config.ru. The file should be a separate file with the

Automatic loading of lib directory

If you want to have the lib directory and below loaded automatically, configure as follows
This way, you don't have to read every single class under the lib directory.
(You don't have to have it loaded, depending on your method.)

config/application.rb

module YourApp
  class Application < Rails::Application
    # Load the files under the lib directory
    # Rails4
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    # Rails5 or Rails6
    config.eager_load_paths << Rails.root.join("lib")
  end
end
Enter fullscreen mode Exit fullscreen mode

Creating the Rack::Auth::Basic extension class

Extend lib/my_basic_auth.rb with the following class for basic authentication Create a file with

class MyBasicAuth < Rack::Auth::Basic
  def call(env)
    request = Rack::Request.new(env)
    # Match regex hits are not basic authentication
    if request.path.match(/^\/.well-known/)
      # Pass basic authentication
      @app.call(env)
    else
      # Execute basic authentication
      super
    end
  end
end

Enter fullscreen mode Exit fullscreen mode

Loading Custom Basic Authentication into the Configuration File for the Staging Environment

config/environment/production.rb

Rails.application.configure do
  if ENV["STAGING"]  #set environmental variable
    # Load MyBasicAuth
    config.middleware.use MyBasicAuth do |username, password|
      username == "YOUR_NAME" && password == "PASSWORD"
    end
  end
  ..
  .
end
Enter fullscreen mode Exit fullscreen mode

refs:
http://stackoverflow.com/questions/6049414/selectively-allow-some-urls-through-rackauthbasic
http://stackoverflow.com/questions/22336048/staging-env-password-protect-everything-except-for-webhook

Top comments (0)