Setup authentication with Devise

Published September 12, 2010 by Toran Billups

So you have a working rails 3 application and you need to apply some type of authentication system?

Install the gem

First be sure you are in the directory of your rails aplication. If so pull down the devise gem

gem install devise

Next you need to modify the Gemfile so devise is included. Type gedit Gemfile and add the line below

gem 'devise'

Next you need to run the install for bundler

bundle install

Next run the full install to get devise setup in your application

rails generate devise:install

After this is run you should see a nice 'todo' list from the devise team (shown below). I will implement each of them below if you haven't already.

devise install todo list

Setup prerequisites for Devise

First you need to delete the index.html file found in the public folder. Next you need to have a controller + action setup to handle the root action.

rails generate controller Welcome index

After you setup this controller to handle your root action make sure you add a line in your routes file to hook this up correctly.

routes with root defined

Next you need to add a line to your development.rb file for the mailer default url found under config/environments

flash markup for welcome

You also need to add a notice and alert container if you don't have one already. I'm adding mine to the application.html.erb file found under app/views/layouts

flash markup for welcome

Generate and configure User with Devise

First you need to run the generate command to add the simple User model for basic authentication

rails generate devise User

Next you need to modify the index.html.erb for welcome so you can sign in / sign out

welcome markup with sign in

Finally you need to migrate the database so User is setup

rake db:migrate

Now if you run the application you should be able to create an account and sign in. But we haven't restricted anyone just yet ...

Add the authenticate filter

In each controller that you need authentication simply add the line below with an optional 'except' param that allows specific actions to be done without authentication.

controller auth code

Now you have a fully working authentication setup with rails 3 and devise!

If you want the source for the finished blog application you can download it here


Buy Me a Coffee

Twitter / Github / Email