Ruby on Rails

How to add Basic HTTP Authentication to Sidekiq UI mounted on a Rails application

When your Ruby on Rails project does not have any form of user authentication, not using devise, or any custom authentication and you need to secure your SIdekiq UI, you can add Sidekiq Basic HTTP Authentication from the application’s routes to the mounted Sidekiq engine.

This minipost will only show how to add Sidekiq Basic Rack Authentication from the application's routes to the mounted Sidekiq engine. If you are looking for other forms of authentication for Sidekiq, you can use devise, however, this post targets the Ruby on Rails applications that are using Sidekiq without any form of user authentication.

Therefore, in order to secure the Sidekiq UI with a basic Rack Authentication, just add the following code block to the Rails application at config/routes.rb:

Rails.application.routes.draw do
  require 'sidekiq/web'
  # ----------------------------------------------------------------------
  # Monitoring
  scope :monitoring do
    # Sidekiq Basic Auth from routes on production environment
    Sidekiq::Web.use Rack::Auth::Basic do |username, password|
      ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(username), ::Digest::SHA256.hexdigest(ENV["SIDEKIQ_AUTH_USERNAME"])) &
        ActiveSupport::SecurityUtils.secure_compare(::Digest::SHA256.hexdigest(password), ::Digest::SHA256.hexdigest(ENV["SIDEKIQ_AUTH_PASSWORD"]))
    end if Rails.env.production?

    mount Sidekiq::Web, at: '/sidekiq'
  # ----------------------------------------------------------------------

In the above snippet, I have used a :monitoring scope. Feel free to add your custom route for the Sidekiq UI. Also, I have used two env vars to store the username and password for the authentication. Finally, connect to your production server and export the two environmental variables:

export SIDEKIQ_AUTH_USERNAME=”sidekiq”
export SIDEKIQ_AUTH_PASSWORD=”s!23HwradSC7kPr&j^$”

You now have Sidekiq mounted on an authenticated route to your production server, enabled only on the production environment.