HTTP Authentication with Rails

Rails comes with built in HTTP Authentication.
This is great if you want to password protect your application before it is released, for example, if you are showcasing a client prototype and do not want anyone else other than the client see it.

To add HTTP authentication to the entire application simply place the following in your application controller:

class ApplicationController < ActionController::Base
  # Only run this filter if in production mode, as don't want to enter password in development
  before_filter :check_access if Rails.env == "production"
  private
  def check_access
    authenticate_or_request_with_http_basic do |user_name, password|
    # Change these to username and password required
    user_name == "myuser" && password == "mypassword"
  end
end

4 Comments

RSS feed for comments on this post. TrackBack URL

  1. uma mahesh varma — September 8, 2009

    nice post. its help alot

    Thank You,
    Uma.

  2. nogeek — November 17, 2009

    Thanks for your comment Uma, glad we could help!

  3. vectran — January 6, 2010

    How secure do you think this is? Is it acceptable to use this on an admin panel for an application with say 2k visitors a month? Cheers.

  4. nogeek — January 6, 2010

    It is not particularly secure see wikipedia. I would recommend either setting an admin role in your login system or something along those lines.

    We generally only use it here in front of a staging site or test server, which are situations whereby the site would not be massively compromised if an attacker gained access.

Leave a comment

Preview: