Token based authentication in Rails 3 (and Rails 2)

This is a simple walkthrough for creating a Rails 3 application that supports token based authentication.

This is written for Rails 3 but should work just fine for Rails 2.x

You can find the source code of the demo app on github:
http://github.com/wnoronha/device-auth-demo

Start off by creating a new application

# rails new device-auth-demo
      create  
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/helpers/application_helper.rb
      create  app/views/layouts/application.html.erb
      create  app/controllers/application_controller.rb
      create  app/mailers
      create  app/models
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/environments/development.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/session_store.rb
      create  config/initializers/inflections.rb
      create  config/initializers/secret_token.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  log
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log
      create  public
      create  public/404.html
      create  public/index.html
      create  public/500.html
      create  public/favicon.ico
      create  public/422.html
      create  public/robots.txt
      create  public/images
      create  public/images/rails.png
      create  public/stylesheets
      create  public/stylesheets/.gitkeep
      create  public/javascripts
      create  public/javascripts/application.js
      create  public/javascripts/controls.js
      create  public/javascripts/effects.js
      create  public/javascripts/dragdrop.js
      create  public/javascripts/prototype.js
      create  public/javascripts/rails.js
      create  script
      create  script/rails
      create  test
      create  test/test_helper.rb
      create  test/performance/browsing_test.rb
      create  test/integration
      create  test/fixtures
      create  test/unit
      create  test/functional
      create  tmp
      create  tmp/sessions
      create  tmp/sockets
      create  tmp/cache
      create  tmp/pids
      create  vendor/plugins
      create  vendor/plugins/.gitkeep

Add devise and warden as a dependency

File: Gemfile (Rails 3)

gem 'warden'                                                                    
gem 'devise', '1.1.2'                                                           

File: config/environment.rb (Rails 2.x)

config.gem 'warden'
config.gem 'devise', :version => '1.0.8'

Installing Devise

rails g devise:install
rails g devise User
rails g devise:views

Setup the default URL for outgoing emails

File: config/environments/development.rb

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

Setup your migrations. Rails 2 does not create the authentication_token column so you need to do this manually.

File: db/migrate/*_devise_create_users.rb (Rails 3)

create_table(:users) do |t|
  t.token_authenticatable
end
 
add_index :users, :authentication_token, :unique => true

File: db/migrate/*_devise_create_users.rb (Rails 2)

create_table(:users) do |t|
  t.string  :authentication_token
end
 
add_index :users, :authentication_token, :unique => true

Migrate your database

rake db:migrate

Enable token based authentication in your user model

devise :database_authenticatable, :registerable,
            :recoverable, :rememberable, :trackable, :validatable,
            :token_authenticatable

Create a demo controller for testing

  rails g scaffold Post title:string body:text

Ensure that no actions other than index and show can be accessed by unauthenticated users.

before_filter :authenticate_user!, :except => [:index, :show]

Creating a post with a bad token

wnoronha@zack:~/workspace/device-auth-demo$ curl -H 'Accept: application/xml' -H 'Content-Type: application/xml' -d '<post><title>Hello</title><body>World</body></post>' <a href="http://localhost:3000/posts.xml?auth_token=badtoken<br />
<?xml" title="http://localhost:3000/posts.xml?auth_token=badtoken<br />
<?xml">http://localhost:3000/posts.xml?auth_token=badtoken<br />
<?xml</a> version="1.0" encoding="UTF-8"?>
<hash>
  <error>Invalid authentication token.</error>
</hash>

Creating a post with the right token

wnoronha@zack:~/workspace/device-auth-demo$ curl -H 'Accept: application/xml' -H 'Content-Type: application/xml' -d '<post><title>Hello</title><body>World</body></post>' <a href="http://localhost:3000/posts.xml?auth_token=goodtoken<br />
<?xml" title="http://localhost:3000/posts.xml?auth_token=goodtoken<br />
<?xml">http://localhost:3000/posts.xml?auth_token=goodtoken<br />
<?xml</a> version="1.0" encoding="UTF-8"?>
<post>
  <created-at type="datetime">2010-09-17T00:46:17Z</created-at>
  <body>World</body>
  <title>Hello</title>
  <updated-at type="datetime">2010-09-17T00:46:17Z</updated-at>
  <id type="integer">1</id>
</post>

3 comments

Ajey's picture

curl syntax curl -u

Submitted by Ajey (not verified) on Mon, 06/06/2011 - 11:00.

curl syntax

curl -u "ElMVlRKdP4tDuDEfW5a4:notrequired" -F 'query="post query string"' http://localhost:3000/keyextractor/show.xml

Ajey's picture

token curl syntax curl -u

Submitted by Ajey (not verified) on Mon, 06/06/2011 - 10:59.

token curl syntax

curl -u "ElMVlRKdP4tDuDEfW5a4:notrequired" -F 'query="post query string"' http://localhost:3000/keyextractor/show.xml

I hope this is useful.

Anonymous's picture

Hi, Thanks for the

Submitted by Anonymous (not verified) on Mon, 05/23/2011 - 20:27.

Hi,

Thanks for the introduction. I'm now planning to use token authentication for mobile in one of my projects.

I'm missing some basic details to complete the idea.

#1- Where does the first token to use comes from? You have bad token and good token but no info about where the token is generated. So if this was a mobile, how do we tell the mobile the token to use? How to do introduce a user into the system so it can use the tokens afterwards?

#2- The curl examples are a bit confusing, for the example the wrong token one, request and response are covered there right?

I'll try to complete this base to get it done.

Cheers.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <pre>, <apache>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. The supported tag styles are: <foo>, [foo].

More information about formatting options

Drupal theme by Kiwi Themes.