Jump To Content

LearnHub




Action Controller: HTTP Basic Authentication

HTTP Basic Authentication

Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the major ity of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser 's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, authenticate_or_request_with_http_basic Authentication/Basic/ControllerMethods.html#M000610.


class AdminController < ApplicationController

  USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c" 

  before_filter :authenticate

private

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == USERNAME && Digest::MD5.hexdigest(password) == PASSWORD
    end
  end

end

With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting th em with HTTP Basic authentication.

Articles in this guide

  1. Introduction
  2. What does a controller do?
  3. Parameters
  4. Sessions
  5. Cookies
  6. Filters
  7. Verification
  8. The request and response objects
  9. HTTP Basic Authentication (This article)
  10. Streaming and file downloads
  11. Parameter filtering
  12. Rescue

Thanks to the Ruby on Rails documentation team

This guide was written by Tore Darrell as part of the Ruby on Rails Documentation Project and is provided freely under a Creative Commons licence


Your Comment
Textile is Enabled (View Reference)