Using basic authentication to hide your website

Anton Jenkins | February 18, 2009

Suppose you’re developing a rails website for a client and you’d like them to be able to access it on a staging server, but you want to keep it hidden from prying eyes until it’s ready to launch. The quickest and cleanest way is to utilise HTTP basic authentication.

By adding the following code to your application.rb you will protect all pages on the site with a username and password dialog :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#app/controllers/application.rb

require 'digest/sha1'

class ApplicationController < ActionController::Base

before_filter :authenticate

protected
  def authenticate
    if Rails.env == "production"
      authenticate_or_request_with_http_basic do |username, password|
        username_hash = Digest::SHA1.hexdigest(username)
        password_hash = Digest::SHA1.hexdigest(password)
        username_hash == "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33" && password_hash == "62cdb7020ff920e5aa642c3d4066950dd1f01f4d"
      end
    end
  end
end

What’s with the “0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33”?

Rather than put the username and password in plain text here I’ve obscured them using SHA1 to make it a little more secure. Suppose we want a username of ‘foo’ and and password of ‘bar’ we can use the rails console to obtain the hashes required and paste them in to the above code snippet.

1
2
3
4
5
6
7
8
#./script/console

>> require 'digest/sha1'
=> []
>> Digest::SHA1.hexdigest("foo")
=> "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
>> Digest::SHA1.hexdigest("bar")
=> "62cdb7020ff920e5aa642c3d4066950dd1f01f4d"

Won’t my tests fail?

This is why we specify the rails environment using :

1
if Rails.env == "production"

By doing this we ensure that our tests wont be asked to authenticate and also our development environment will be left alone. If Rails.env doesn’t work for you then try changing this to RAILS_ENV.

Disabling the authentication

Turning it all off is as simple as removing the before filter from your application.rb :

1
before_filter :authenticate  # comment out or remove this line

You may as well leave the authenticate method sitting in your apllication.rb just in case you need to lock things down quickly at a future date.

Other uses for this technique

This method is also very useful for securing the admin areas of your site as detailed in this railscast. If you require something a bit more comprehensive you might want to check out Lockdown, AuthLogic or Restful Authentication.

comments powered by Disqus