Is there a way to set up simple http authentication for a Ruby on Rails app on heroku?

Viewed 22569

I want to set up a private staging server on heroku using simple http authentication. Is that possible?

6 Answers

Updated answer for Rails 5+. In your config/application.rb or selected environment config:

config.middleware.use(Rack::Auth::Basic) do |u, p|
  [u, p] == [ENV['USER'], ENV['PASSWORD'] || SecureRandom.hex]
end

It's been pointed out in Ole's blog post to use ENV vars. I'd add that defaulting to a random password is a good idea in case the env var is not set.

To use it only on certain paths you can create your own middleware (refer to this answer):

class AdminAuth < Rack::Auth::Basic
  def call(env)
    req = Rack::Request.new(env)

    return @app.call(env) unless admin_path?(req)

    super
  end

  def admin_path?(req)
    req.path =~ /^\/admin\/*/
  end
end
Related