DEV Community 👩‍💻👨‍💻


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"

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 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.)


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")

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 =
    # Match regex hits are not basic authentication
    if request.path.match(/^\/.well-known/)
      # Pass basic authentication
      # Execute basic authentication

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


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


Top comments (0)

18 Useful Github Repositories Every Developer Should Bookmark

18 Useful GitHub repositories every developer should bookmark: everything from learning resources and roadmaps to best practices, system designs, and tools.