Last Updated: February 25, 2016
·
2.586K
· xtagon

Restrict access to your Rails staging environment

Need a quick and dirty way to restrict access to your Rails app? Perhaps you don't want just anyone to access your staging environment, and you haven't implemented user authentication yet.

First, put something like this in config/initializers/staging_auth.rb

YourRailsApp::Application.configure do
    # Restrict access with HTTP Basic Auth for staging environments
    unless ENV['STAGING_AUTH'].blank?
        config.middleware.use '::Rack::Auth::Basic' do |username, password|
            ENV['STAGING_AUTH'].split(';').any? do |pair|
                [username, password] == pair.split(':')
            end
        end
    end
end

Then, set the environment variable STAGING_AUTH for any deploy that you want to lock down with HTTP Basic Auth. The format is:

STAGING_AUTH="user:pass"

or, if you want multiple user credentials, separate them with a semicolon

STAGING_AUTH="user1:pass1;user2:pass2"

Here's an example if you're deploying to Heroku:

heroku config:set STAGING_AUTH="foobar:hunter2"

1 Response
Add your response

Thank you!

over 1 year ago ·