Tuesday, 3 June 2008

Rails Basic HTTP Authentication

Some web applications require authentication for accessing some or all resources. The simple case in authentication is depending on http protocol and its authentication mechanism.

There are deferent types for http authentication, the simplest one is Basic Access Authentication. It depends on encoding the user name and password using Base64 encoding and put it in the http authorization header.

Rails helps you in using http basic authentication, or as they say in its documentation "Makes it dead easy to do HTTP Basic authentication". All you need to do is very simple:


  1. Create a separated module, may be called "Authentication"

    module Authentication

    end

  2. Create a method inside the module that will do your authentication

    def authenticate

       authenticate_or_request_with_http_basic do |username, password|

       end

    end

    Note that I put a call to authenticate_or_request_with_http_basic method in ActionController::HttpAuthentication::Basic Module that will provide you with the sent user name and password after decoding them using Base64 decoder.

  3. Now, you need to call the authentication method before every call to your controllers. That will done by putting a "before_filter" call in your ApplicationController class:

    class ApplicationController < ActionController::Base

       include Authentication

       before_filter :authenticate

    .....

    end


  4. If you need to skip some controllers from authentication chain, put in this controller a call to skip_before_filter:

    skip_before_filter :authenticate


  5. The last step is filling your authentication method with the code that will do the authentication check using the given user name and password.


No comments: