github facebook twitter

HTTP Basic Auth Recipe

require "kemal"
require "kemal-basic-auth"

basic_auth "username", "password"

get "/" do |env|
  "This is shown if basic auth successful."
end

Kemal.run

This will add basic authorization to all routes in your application. However, some applications only need authorization on some of its routes. This is something can be easily done by creating a custom authorization handler.

require "kemal-basic-auth"

class CustomAuthHandler < Kemal::BasicAuth::Handler
  only ["/dashboard", "/admin"] # routes with basic authorization

  def call(context)
    return call_next(context) unless only_match?(context)
    super
  end
end

Kemal.config.auth_handler = CustomAuthHandler

Source Code