Rails http basic authentication for more than one user?

Viewed 2055

So I have a very basic static pages rails app, and I want to create a number of usernames and passwords for people to access these static pages. Naturally, the rails api has the http_basic_atenticate, but how are you supposed to have more than one user?

To be clear, I want to only use http_basic for more than one user. How to go about this?

Eg; user1 has password1, user2 has password2, user3 has password3, and so forth?

class StaticController < ApplicationController

http_basic_authenticate_with :name => "user", :password => "password"


  def home
  end

  def content
  end

end
3 Answers

Simple solution:

h = Hash[user1: "Password1", user2: "Password2"]
authenticate_or_request_with_http_basic do |id, password|
  if h.has_key?(id.to_sym)
    password == h[id.to_sym]
  end
end      

While the previous answers are certainly 100% correct, I'd like to share an approach which is a little more generic and re-usable (but basically uses the same methods as the previous answers):

app/controllers/concerns/guest_list_auth.rb

module GuestListAuth
  extend ActiveSupport::Concern

  included do
    cattr_accessor :guest_list
    self.guest_list = :everyone_is_invited

    before_action :perform_guest_list_auth
  end

  class_methods do
    def authenticate_against_guest_list(guest_list)
      self.guest_list = guest_list
    end
  end

  protected
  def perform_guest_list_auth
    return if guest_list == :everyone_is_invited
    authenticate_or_request_with_http_basic('Application') do |name, password|
      guest_list.present? &&
        guest_list.has_key?(name.to_sym) &&
        guest_list[name.to_sym] == password.to_s
    end
  end
end

app/controllers/static_controller.rb

class StaticController < ApplicationController
  include GuestListAuth
  authenticate_against_guest_list (
    {
      demo01: '...',
      demo02: '...',
      demo03: '...',
    }
  )

  def home
  end

  # ...
end
Related