authlogic 0,-1,2,0,1,0,0,0 rubocop travis-ci ruby Rubygems

A simple ruby authentication solution.


A clean, simple, and unobtrusive ruby authentication solution.

Gem Version Build Status Code Climate Dependency Status


Timber Logging

Tail Authlogic users in your logs!


Version Documentation

Table of Contents

1. Introduction

1.a. Compatibility

Version branches tag ruby activerecord
Unreleased master, 4-stable >= 2.1.0 >= 3.2, < 5.2
3 3-stable v3.6.0 >= 1.9.3 >= 3.2, < 5.2
2 rails2 v2.1.11 >= 1.9.3 ~> 2.3.0
1 ? v1.4.3 ? ?

1.b. Overview

It introduces a new type of model. You can have as many as you want, and name them whatever you want, just like your other models. In this example, we want to authenticate with the User model, which is inferred by the name:

class UserSession < Authlogic::Session::Base
  # specify configuration here, such as:
  # logout_on_timeout true
  # ...many more options in the documentation

In a UserSessionsController, login the user by using it just like your other models:

UserSession.create(:login => "bjohnson", :password => "my password", :remember_me => true)

session = => "bjohnson", :password => "my password", :remember_me => true)

# requires the authlogic-oid "add on" gem
UserSession.create(:openid_identifier => "identifier", :remember_me => true)

# skip authentication and log the user in directly, the true means "remember me"
UserSession.create(my_user_object, true)

The above handles the entire authentication process for you by:

  1. authenticating (i.e. validating the record)
  2. sets up the proper session values and cookies to persist the session (i.e. saving the record).

You can also log out (i.e. destroying the session):


After a session has been created, you can persist it (i.e. finding the record) across requests. Thus keeping the user logged in:

session = UserSession.find

To get all of the nice authentication functionality in your model just do this:

class User < ActiveRecord::Base
  acts_as_authentic do |c|
    c.my_config_option = my_value
  end # the configuration block is optional

This handles validations, etc. It is also “smart” in the sense that it if a login field is present it will use that to authenticate, if not it will look for an email field, etc. This is all configurable, but for 99% of cases that above is all you will need to do.

You may specify how passwords are cryptographically hashed (or encrypted) by setting the Authlogic::CryptoProvider option:

c.crypto_provider = Authlogic::CryptoProviders::BCrypt

You may validate international email addresses by enabling the provided alternate regex:

c.validates_format_of_email_field_options = {:with => Authlogic::Regex.email_nonascii}

Also, sessions are automatically maintained. You can switch this on and off with configuration, but the following will automatically log a user in after a successful registration:


You can switch this on and off with the following configuration:

class User < ActiveRecord::Base
  acts_as_authentic do |c|
    c.log_in_after_create = false
  end # the configuration block is optional

Authlogic also updates the session when the user changes his/her password. You can also switch this on and off with the following configuration:

class User < ActiveRecord::Base
  acts_as_authentic do |c|
    c.log_in_after_password_change = false
  end # the configuration block is optional

Authlogic is very flexible, it has a strong public API and a plethora of hooks to allow you to modify behavior and extend it. Check out the helpful links below to dig deeper.

1.c. How to use this documentation

You can find anything you want about Authlogic in the documentation, all that you need to do is understand the basic design behind it.

That being said, there are 2 models involved during authentication. Your Authlogic model and your ActiveRecord model:

  1. Authlogic::Session, your session models that extend Authlogic::Session::Base.
  2. Authlogic::ActsAsAuthentic, which adds in functionality to your ActiveRecord model when you call acts_as_authentic.

Each of the above has its various sub modules that contain common logic. The sub modules are responsible for including everything related to it: configuration, class methods, instance methods, etc.

For example, if you want to timeout users after a certain period of inactivity, you would look in Authlogic::Session::Timeout. To help you out, I listed the following publicly relevant modules with short descriptions. For the sake of brevity, there are more modules than listed here, the ones not listed are more for internal use, but you can easily read up on them in the documentation.

2. Rails

What if creating sessions worked like an ORM library on the surface…


2.a. The users table

If you want to enable all the features of Authlogic, a migration to create a +User+ model, for example, might look like this:

class CreateUser < ActiveRecord::Migration
  def change
    create_table :users do |t|
      # Authlogic::ActsAsAuthentic::Email
      t.string    :email

      # Authlogic::ActsAsAuthentic::Password
      t.string    :crypted_password
      t.string    :password_salt

      # Authlogic::ActsAsAuthentic::PersistenceToken
      t.string    :persistence_token
      t.index     :persistence_token, unique: true

      # Authlogic::ActsAsAuthentic::SingleAccessToken
      t.string    :single_access_token
      t.index     :single_access_token, unique: true

      # Authlogic::ActsAsAuthentic::PerishableToken
      t.string    :perishable_token
      t.index     :perishable_token, unique: true

      # Authlogic::Session::MagicColumns
      t.integer   :login_count, default: 0, null: false
      t.integer   :failed_login_count, default: 0, null: false
      t.datetime  :last_request_at
      t.datetime  :current_login_at
      t.datetime  :last_login_at
      t.string    :current_login_ip
      t.string    :last_login_ip

      # Authlogic::Session::MagicStates
      t.boolean   :active, default: false
      t.boolean   :approved, default: false
      t.boolean   :confirmed, default: false


2.b. Controller

What if your user sessions controller could look just like your other controllers?

class UserSessionsController < ApplicationController
  def new
    @user_session =

  def create
    @user_session =
      redirect_to account_url
      render :action => :new

  def destroy
    redirect_to new_user_session_url


  def user_session_params
    params.require(:user_session).permit(:email, :password)

As you can see, this fits nicely into the RESTful development pattern.

How about persisting the session?

class ApplicationController
  helper_method :current_user_session, :current_user

    def current_user_session
      return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.user

2.c. View

<%= form_for @user_session do |f| %>
  <% if @user_session.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@user_session.errors.count, "error") %> prohibited:</h2>
      <% @user_session.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
  <% end %>
  <%= f.label :login %><br />
  <%= f.text_field :login %><br />
  <br />
  <%= f.label :password %><br />
  <%= f.password_field :password %><br />
  <br />
  <%= f.submit "Login" %>
<% end %>

2.d. CSRF Protection

Because Authlogic introduces its own methods for storing user sessions, the CSRF (Cross Site Request Forgery) protection that is built into Rails will not work out of the box.

No generally applicable mitigation by the authlogic library is possible, because the instance variable you use to store a reference to the user session in def current_user_session will not be known to authlogic.

You will need to override ActionController::Base#handle_unverified_request to do something appropriate to how your app handles user sessions, e.g.:

class ApplicationController < ActionController::Base

  def handle_unverified_request
    # raise an exception
    fail ActionController::InvalidAuthenticityToken
    # or destroy session, redirect
    if current_user_session
    redirect_to root_url

3. Testing

See Authlogic::TestCase

4. Helpful links

5. Add-ons

If you create one of your own, please let us know about it so we can add it to this list. Or just fork the project, add your link, and send us a pull request.

6. Internals

Interested in how all of this all works? Think about an ActiveRecord model. A database connection must be established before you can use it. In the case of Authlogic, a controller connection must be established before you can use it. It uses that controller connection to modify cookies, the current session, login with HTTP basic, etc. It connects to the controller through a before filter that is automatically set in your controller which lets Authlogic know about the current controller object. Then Authlogic leverages that to do everything, it’s a pretty simple design. Nothing crazy going on, Authlogic is just leveraging the tools your framework provides in the controller object.

Intellectual Property

Copyright © 2012 Ben Johnson of Binary Logic, released under the MIT license

Related Repositories



A simple ruby authentication solution. ...



Facebook Connect for Authlogic ...



Authlogic OAuth is an extension of the Authlogic library to add OAuth support. OAuth can be used to allow users to login with their Twitter credentials. ...



Youtube-like site written in Rails. Uses ffmpeg, flowplayer, attachment_fu, authlogic, acts_as_taggable_on_steroids ...



Authlogic, OpenID, Oauth, Rails 3, on Heroku ...

Top Contributors

binarylogic tiegz jaredbeck rchekaluk m4n nathany bnauta naberon roryokane bensomers james2m jjb christophemaximin Hermanverschooten chewi boone petergoldstein radar ZenCocoon jefmathiot avit bcardarella hybernaut dpbus dcrec1 josephruscio leejones malclocke neilmiddleton rofreg


-   v.3.5.0 zip tar
-   v3.4.6 zip tar
-   v3.4.5 zip tar
-   v3.4.4 zip tar
-   v3.4.3 zip tar
-   v3.4.2 zip tar
-   v3.4.1 zip tar
-   v3.4.0 zip tar
-   v3.3.0 zip tar
-   v3.2.0 zip tar
-   v3.1.3 zip tar
-   v3.1.2 zip tar
-   v3.1.1 zip tar
-   v3.1.0 zip tar
-   v3.0.3 zip tar
-   v3.0.2 zip tar
-   v3.0.1 zip tar
-   v3.0.0 zip tar
-   v2.1.11 zip tar
-   v2.1.10 zip tar
-   v2.1.9 zip tar
-   v2.1.6 zip tar
-   v2.1.5 zip tar
-   v2.1.4 zip tar
-   v2.1.3 zip tar
-   v2.1.2 zip tar
-   v2.1.1 zip tar
-   v2.1.0 zip tar
-   v2.0.14 zip tar
-   v2.0.13 zip tar