Rails Security


Basic HTTP authentication is not secure. However, for whatever, if we really want to use it, how can we use it?

In the ArticlesController we need to have a way to block access to the various actions if the person is not authenticated, here we can use the Rails http_basic_authenticate_with method, allowing access to the requested action if that method allows it.

To use the authentication system, we specify it at the top of our ArticlesController, in this case, we want the user to be authenticated on every action, except for index and show, so we write that in app/controllers/articles_controller.rb:

class ArticlesController < ApplicationController

  http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]

  def index
    @articles = Article.all

We also want to allow only authenticated users to delete comments, so in the CommentsController (app/controllers/comments_controller.rb) we write:

class CommentsController < ApplicationController

  http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy

  def create
    @article = Article.find(params[:article_id])

What are popular authentication gems for Rails?

Two popular authentication add-ons for Rails are the Devise rails engine and the Authlogic gem.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License