HTTP basic authentication in rails to protect staging server

Sometimes, you may need to protect your staging server from outside world. It can be done easily by using http basic authentication in rails3.

I did following things to use HTTP basic authentication to protect my staging server:

YML file with username and password pair:

devuser: devpass
testuser: testuserpass

Loaded YML data from application initializer:

HTTP_AUTH_USERS = YAML.load_file("#{Rails.root.to_s}/config/staging_server_users.yml")

Callback and authentication in the application controller:

before_filter :authenticate_for_staging_server, :if => lambda { Rails.env.development? }

def authenticate_for_staging_server
authenticate_or_request_with_http_basic do |user_name, password|
password == HTTP_AUTH_USERS[user_name]

Hope it will help a lot who wants to protect their staging server.

Leave a Comment