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

后端 未结 6 1653
夕颜
夕颜 2020-12-07 16:07

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

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 16:47

    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
    

提交回复
热议问题