Ruby on Rails: HTTP Basic Authentication
Often you’ll want one user authentication such as protection for administration features. A great way to do this is to use HTTP basic authentication (which is very easy to incorporate to an RoR application).
We’re going to open up the controller of which the actions you wish to protect are in, setup a before_filter and then create the method for our authentication (of course you could reverse the order of the last two steps).
Let’s say that we wanted to change it so that the new and edit actions for our simple blog’s post controller were protected. Firstly we’d go into posts_controller.rb (app/controllers/posts_controller.rb) and we’d add a before_filter that points to the ‘authenticate’ method (which we’ll create shortly) whenever the new and edit actions are used. Basically we want all actions except index (for listing our posts) and show (for showing a post) to be protected by ‘authenticate’:
before_filter :authenticate, :except => [:index, :show]
Now that we’ve set out before_filter to point to the authenticate method – we need to create this method. This method is the one that actually handles the HTTP authentication:
def authenticate authenticate_or_request_with_http_basic do |username, password| username == "username" && password == "password" end end
This just tells it that the correct username is “username” and the correct password is “password” (you won’t get in without these correct values). We could also put this authenticate method inside our application controller (app/controllers/application_controller.rb) if we want to use the ‘authenticate’ method in more than one controller (instead of copying the authenticate method elsewhere) however in this example since we only want to protect the posts it’s fine in the posts_controller.
Our authentication should now work!
Note t hat since HTTP basic authentication is handled by the browser, you need to close the browser to destroy the session. If you really want to destroy the session yourself then there are some hacks around to do this however I have not looked into them.
Back to Ruby on Rails

