cgmksa
Last Updated: February 25, 2016
·
1.937K
· xtagon
B51e7cdcc7a02568f78c50c5eeee2439

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"

Say Thanks
Respond

1 Response
Add your response

15961
267e8c8b247b880aa9a4e54932b797a9

Thank you!

over 1 year ago ·