Simplest authentication in Rails: Basic Authentication with a logged_in? helper.

The, by far, simplest solution to add some form of authentication in Rails is basic authentication. It has a lot of downsides, but the simplicity is such a benefit that it may just outweight.

Downsides are, amongst others:

  • No users, no user-manangement.
  • Your username and password are hardcoded in the application.
  • No fancy or good looking login screens: just the basic HTTP login provided by your browser.
  • No logout, other then closing the browser.

Here is a simple implementation for a simple app I needed. Since I am the only editor, there is no need to introduce session controllers, user models and so on. If you are relatively new to Rails (like me) you may miss this most simple solution and dive right into devise or authlogic or start writing your own. And miss out that 10-minutes-and-you’re-done solution.

First, we introduce a basic authenticate method, that can be used troughout our controllers. This method uses the Rails/Rack helper authenticate_or_request_with_http_basic.

class ApplicationController < ActionController::Base
  protect_from_forgery

  protected
    def authenticate
      authenticate_or_request_with_http_basic do |username, password|
        username == USER_ID && password == PASSWORD
      end
    end
end

In a controller, we can then add a before_filter to require authentication for all methods but the index and the show.

class ImagesController < ApplicationController
  before_filter :authenticate, :except => [:index, :show]
  #...
end

A new file under config/initializers, named user.rb or anything else you want, contains the hardcoded username or password. Putting it in a separate file allows you to leave it out of your version-control, for example.

USER_ID   = "Sauron"
PASSWORD  = "s3cr3t"

Furhtermore, we define a logged_in? helper, usefull in our views. This checks if the authorization is a string (it is set) or nil (user is not authorized):

module ApplicationHelper
 def logged_in?
   not request.authorization.nil?
 end
end

Using that helper is simple too. E.g. show.html.erb:

<% if logged_in? %>
  <li><%= link_to 'Edit', edit_image_path(@image) %></li>
<% end %>

I am not certain if this evaluation of request.authorization.nil? performs all that well, but I would say, it being simple as possible, that the overhead is minimal.

This article was published on webschuur.com. And migrated to this blog.

in ruby28 ruby on rails14

About the author: Bèr Kessels is an experienced webdeveloper with a great passion for technology and Open Source. A golden combination to implement that technology in a good and efficient way. Follow @berkes on Mastodon. Or read more about Bèr.