Top Related Projects
Flexible authentication solution for Rails with Warden.
OmniAuth is a flexible authentication system utilizing Rack middleware.
Forms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.
Rails authentication with email & password.
Magical authentication for Rails 3 & 4
Authorization Gem for Ruby on Rails.
Quick Overview
Authlogic is a clean, simple, and unobtrusive Ruby authentication solution. It provides a flexible framework for user authentication in Ruby on Rails applications, allowing developers to implement secure login systems with ease.
Pros
- Highly customizable and flexible authentication solution
- Seamless integration with Ruby on Rails applications
- Supports various authentication methods (e.g., password, single sign-on)
- Active community and well-maintained documentation
Cons
- Learning curve for beginners due to its flexibility
- Some features may require additional gems or plugins
- Not as feature-rich out-of-the-box compared to some alternatives
Code Examples
- Basic User model setup:
class User < ApplicationRecord
acts_as_authentic do |c|
c.crypto_provider = Authlogic::CryptoProviders::BCrypt
end
end
- Creating a user session controller:
class UserSessionsController < ApplicationController
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(user_session_params)
if @user_session.save
redirect_to account_url
else
render :new
end
end
private
def user_session_params
params.require(:user_session).permit(:email, :password, :remember_me)
end
end
- Implementing login/logout functionality:
class ApplicationController < ActionController::Base
helper_method :current_user_session, :current_user
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
end
Getting Started
- Add Authlogic to your Gemfile:
gem 'authlogic'
- Run bundle install:
bundle install
- Generate User model and migration:
rails generate model User email:string crypted_password:string password_salt:string persistence_token:string
- Update the User model:
class User < ApplicationRecord
acts_as_authentic
end
- Create a UserSession model:
class UserSession < Authlogic::Session::Base
end
- Set up controllers and views for user registration, login, and logout functionality.
Competitor Comparisons
Flexible authentication solution for Rails with Warden.
Pros of Devise
- More comprehensive authentication solution with built-in modules for various features
- Actively maintained with frequent updates and a large community
- Easier to set up and configure out of the box
Cons of Devise
- Can be overkill for simple authentication needs
- Less flexible for customization compared to Authlogic
- Steeper learning curve due to its extensive feature set
Code Comparison
Devise configuration:
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
Authlogic configuration:
acts_as_authentic do |c|
c.crypto_provider = Authlogic::CryptoProviders::BCrypt
end
Devise offers a more declarative approach with pre-defined modules, while Authlogic provides a more customizable configuration block.
Both libraries have their strengths, with Devise being more feature-rich and easier to set up, while Authlogic offers more flexibility for custom authentication solutions. The choice between them depends on the specific needs of the project and the desired level of control over the authentication process.
OmniAuth is a flexible authentication system utilizing Rack middleware.
Pros of OmniAuth
- Supports multiple authentication providers (e.g., Facebook, Google, Twitter)
- Easily extendable with custom strategies
- Provides a consistent interface for various authentication methods
Cons of OmniAuth
- Requires additional setup for each provider
- May introduce security risks if not properly configured
- Can be overkill for simple authentication needs
Code Comparison
Authlogic (User model):
acts_as_authentic do |c|
c.crypto_provider = Authlogic::CryptoProviders::BCrypt
end
OmniAuth (Rails initializer):
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET']
end
Key Differences
- Authlogic focuses on traditional username/password authentication
- OmniAuth is designed for third-party authentication integration
- Authlogic handles password encryption and user sessions internally
- OmniAuth delegates authentication to external providers
Use Cases
- Authlogic: Best for applications requiring simple, self-contained authentication
- OmniAuth: Ideal for apps needing social login or multiple authentication options
Community and Maintenance
- Authlogic: Mature project with less frequent updates
- OmniAuth: Active development and regular updates to support new providers
Forms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.
Pros of Simple Form
- More actively maintained with recent updates and releases
- Offers a wider range of form customization options
- Integrates well with other popular Rails gems like Devise
Cons of Simple Form
- Steeper learning curve due to more complex configuration options
- May introduce unnecessary complexity for simple forms
- Requires additional setup and configuration compared to Authlogic
Code Comparison
Simple Form:
<%= simple_form_for @user do |f| %>
<%= f.input :username %>
<%= f.input :email %>
<%= f.input :password %>
<%= f.button :submit %>
<% end %>
Authlogic:
<%= form_for @user_session do |f| %>
<%= f.label :login %>
<%= f.text_field :login %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit "Login" %>
<% end %>
While both gems serve different purposes (Simple Form for form building and Authlogic for authentication), this comparison highlights their approach to form creation. Simple Form provides a more concise and feature-rich syntax for form generation, while Authlogic focuses on authentication-specific functionality with a more traditional form structure.
Rails authentication with email & password.
Pros of Clearance
- Simpler and more lightweight, focusing on core authentication features
- Better maintained with more recent updates and active community support
- Follows Rails conventions more closely, making it easier to integrate
Cons of Clearance
- Less flexible and customizable compared to Authlogic
- Fewer built-in features, requiring additional gems for advanced functionality
- Limited support for non-Rails frameworks
Code Comparison
Clearance user model:
class User < ApplicationRecord
include Clearance::User
end
Authlogic user model:
class User < ApplicationRecord
acts_as_authentic do |c|
c.crypto_provider = Authlogic::CryptoProviders::BCrypt
end
end
Clearance focuses on simplicity and convention, requiring minimal setup. Authlogic offers more configuration options but requires more initial setup.
Both libraries provide secure authentication, but Clearance is better suited for straightforward Rails applications, while Authlogic offers more flexibility for complex or non-Rails projects. Clearance's active maintenance and community support give it an edge for long-term stability, but Authlogic's extensive customization options may be preferable for projects with specific authentication requirements.
Magical authentication for Rails 3 & 4
Pros of Sorcery
- More modular and flexible architecture, allowing developers to choose and configure specific authentication components
- Easier to customize and extend with hooks and callbacks
- Supports multiple ORMs (Active Record, Mongoid, DataMapper) out of the box
Cons of Sorcery
- Less mature and potentially less stable compared to Authlogic
- Smaller community and fewer resources available
- May require more initial setup and configuration
Code Comparison
Sorcery:
class User < ApplicationRecord
authenticates_with_sorcery!
end
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
auto_login(@user)
redirect_to root_path
else
render :new
end
end
end
Authlogic:
class User < ApplicationRecord
acts_as_authentic
end
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
UserSession.create(@user)
redirect_to root_path
else
render :new
end
end
end
Both libraries provide similar functionality, but Sorcery offers a more modular approach with authenticates_with_sorcery!
and auto_login
, while Authlogic uses acts_as_authentic
and UserSession.create
for authentication.
Authorization Gem for Ruby on Rails.
Pros of CanCan
- Simpler and more intuitive authorization system
- Centralized ability definitions in a single file
- Easier to manage complex authorization rules across multiple models
Cons of CanCan
- Less granular control over individual model instances
- May require more custom logic for complex scenarios
- Not actively maintained (last update in 2013)
Code Comparison
CanCan:
class Ability
include CanCan::Ability
def initialize(user)
can :read, Post
can :manage, Post, user_id: user.id
end
end
Authlogic:
class User < ApplicationRecord
acts_as_authentic do |c|
c.crypto_provider = Authlogic::CryptoProviders::BCrypt
end
end
Key Differences
- Authlogic focuses on authentication, while CanCan handles authorization
- Authlogic provides more flexibility in user session management
- CanCan offers a more declarative approach to defining permissions
- Authlogic requires more setup but provides finer control over the authentication process
- CanCan integrates well with Rails' built-in helpers for authorization checks
Both libraries serve different purposes in a Rails application's security stack. Authlogic handles user authentication, ensuring users are who they claim to be, while CanCan manages authorization, determining what actions users are allowed to perform. In many cases, developers use both libraries together to create a comprehensive security solution for their Rails applications.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Authlogic
An unobtrusive ruby authentication library based on ActiveRecord.
Documentation
Table of Contents
- 1. Introduction
- 2. Rails
- 3. Testing
- 4. Helpful links
- 5. Add-ons
- 6. Internals
- 7. Extending
- 90. Compatibility
1. Introduction
1.a. Overview
Authlogic 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 our User
model, which is inferred from the name:
class UserSession < Authlogic::Session::Base
# specify configuration here, such as:
# logout_on_timeout true
# ...many more options in the documentation
end
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 = UserSession.new(:login => "bjohnson", :password => "my password", :remember_me => true)
session.save
# 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:
- authenticating (i.e. validating the record)
- 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):
session.destroy
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 < ApplicationRecord
acts_as_authentic do |c|
c.my_config_option = my_value
end # the configuration block is optional
end
It is also "smart" in the sense that if a login or username field is present it will use that to authenticate, if not it will look for an email field. This is all configurable, but for 99% of cases the 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
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:
User.create(params[:user])
You can switch this on and off with the following configuration:
class User < ApplicationRecord
acts_as_authentic do |c|
c.log_in_after_create = false
end # the configuration block is optional
end
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 < ApplicationRecord
acts_as_authentic do |c|
c.log_in_after_password_change = false
end # the configuration block is optional
end
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.b. Reference Documentation
This README is just an introduction, but we also have reference documentation.
To use the reference documentation, you must understand how Authlogic's code is organized. There are 2 models, your Authlogic model and your ActiveRecord model:
- Authlogic::Session, your session models that
extend
Authlogic::Session::Base
. - Authlogic::ActsAsAuthentic, which adds in functionality to your
ActiveRecord model when you call
acts_as_authentic
.
1.c. Installation
To install Authlogic, add this to your Gemfile:
gem 'authlogic'
And run bundle install
.
2. Rails
Let's walk through a typical rails setup. (Compatibility)
2.a.1 The users table
If you want to enable all the features of Authlogic, a migration to create a
User
model might look like this:
class CreateUser < ActiveRecord::Migration
def change
create_table :users do |t|
# Authlogic::ActsAsAuthentic::Email
t.string :email
t.index :email, unique: true
# Authlogic::ActsAsAuthentic::Login
t.string :login
# 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
# See "Magic Columns" in Authlogic::Session::Base
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
# See "Magic States" in Authlogic::Session::Base
t.boolean :active, default: false
t.boolean :approved, default: false
t.boolean :confirmed, default: false
t.timestamps
end
end
end
In the User
model,
class User < ApplicationRecord
acts_as_authentic
# Validate email, login, and password as you see fit.
#
# Authlogic < 5 added these validation for you, making them a little awkward
# to change. In 4.4.0, those automatic validations were deprecated. See
# https://github.com/binarylogic/authlogic/blob/master/doc/use_normal_rails_validation.md
validates :email,
format: {
with: /@/,
message: "should look like an email address."
},
length: { maximum: 100 },
uniqueness: {
case_sensitive: false,
if: :will_save_change_to_email?
}
validates :login,
format: {
with: /\A[a-z0-9]+\z/,
message: "should use only letters and numbers."
},
length: { within: 3..100 },
uniqueness: {
case_sensitive: false,
if: :will_save_change_to_login?
}
validates :password,
confirmation: { if: :require_password? },
length: {
minimum: 8,
if: :require_password?
}
validates :password_confirmation,
length: {
minimum: 8,
if: :require_password?
}
end
2.a.2. UserSession model
And define a corresponding model in app/models/user_session.rb
:
class UserSession < Authlogic::Session::Base
end
2.b. Controller
Your sessions controller will look just like your other controllers.
class UserSessionsController < ApplicationController
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(user_session_params.to_h)
if @user_session.save
redirect_to root_url
else
render :new, status: 422
end
end
def destroy
current_user_session.destroy
redirect_to new_user_session_url
end
private
def user_session_params
params.require(:user_session).permit(:login, :password, :remember_me)
end
end
As you can see, this fits nicely into the conventional controller methods.
2.b.1. Helper Methods
class ApplicationController < ActionController::Base
helper_method :current_user_session, :current_user
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
end
2.b.2. Routes
Rails.application.routes.draw do
# ...
resources :users
resource :user_session
end
2.b.3. ActionController::API
Because ActionController::API does not include ActionController::Cookies metal and ActionDispatch::Cookies rack module, Therefore, our controller can not use the cookies method.
- #684.
2.c. View
For example, in app/views/user_sessions/new.html.erb
:
<%= form_for @user_session, url: user_session_url do |f| %>
<% if @user_session.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user_session.errors.count, "error") %> prohibited:</h2>
<ul>
<% @user_session.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.label :login %><br />
<%= f.text_field :login %><br />
<br />
<%= f.label :password %><br />
<%= f.password_field :password %><br />
<br />
<%= f.label :remember_me %><br />
<%= f.check_box :remember_me %><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
...
protected
def handle_unverified_request
# raise an exception
fail ActionController::InvalidAuthenticityToken
# or destroy session, redirect
if current_user_session
current_user_session.destroy
end
redirect_to root_url
end
end
2.e. SameSite Cookie Attribute
The SameSite attribute tells browsers when and how to fire cookies in first- or third-party situations. SameSite is used by a variety of browsers to identify whether or not to allow a cookie to be accessed.
Up until recently, the standard default value when SameSite was not explicitly defined was to allow cookies in both first- and third-party contexts. However, starting with Chrome 80+, the SameSite attribute will not default to Lax behavior meaning cookies will only be permitted in first-party contexts.
Authlogic can allow you to explicitly set the value of SameSite to one of: Lax, Strict, or None. Note that when setting SameSite to None, the secure
flag must also be set (secure is the default in Authlogic).
Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#SameSite
3. Testing
4. Helpful links
- API Reference: http://www.rubydoc.info/github/binarylogic/authlogic
- Repository: https://github.com/binarylogic/authlogic/tree/master
- Railscasts Screencast: http://railscasts.com/episodes/160-authlogic
- Example repository with tutorial in README: https://github.com/binarylogic/authlogic_example/tree/master
- Tutorial: Rails Authentication with Authlogic https://www.sitepoint.com/rails-authentication-with-authlogic
- Issues: https://github.com/binarylogic/authlogic/issues
- Chrome is not logging out on browser close https://productforums.google.com/forum/#!topic/chrome/9l-gKYIUg50/discussion
5. Add-ons
- Authlogic OpenID addon: https://github.com/binarylogic/authlogic_openid
- Authlogic LDAP addon: https://github.com/binarylogic/authlogic_ldap
- Authlogic Facebook Connect: https://github.com/kalasjocke/authlogic-facebook-connect
- Authlogic Facebook Connect (New JS API): https://github.com/studybyte/authlogic_facebook_connect
- Authlogic Facebook Shim https://github.com/james2m/authlogic_facebook_shim
- Authlogic OAuth (Twitter): https://github.com/jrallison/authlogic_oauth
- Authlogic Oauth and OpenID: https://github.com/lancejpollard/authlogic-connect
- Authlogic PAM: https://github.com/nbudin/authlogic_pam
- Authlogic x509: https://github.com/auth-scc/authlogic_x509
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.
7. Extending
7.a. Extending UserSession
Your UserSession
is designed to be extended with callbacks.
Example: Custom logging.
# user_session.rb
class UserSession < Authlogic::Session::Base
after_persisting :my_custom_logging
private
def my_custom_logging
Rails.logger.info(
format(
'After authentication attempt, user id is %d',
record.send(record.class.primary_key)
)
)
end
end
To learn more about available callbacks, see the "Callbacks" documentation
in authlogic/session/base.rb
.
90. Compatibility
Version | branch | ruby | activerecord |
---|---|---|---|
6.4.3 | 6-4-stable | >= 2.4.0 | >= 5.2, < 7.2 |
5.2 | 5-2-stable | >= 2.3.0 | >= 5.2, < 6.1 |
4.5 | 4-5-stable | >= 2.3.0 | >= 4.2, < 5.3 |
4.3 | 4-3-stable | >= 2.3.0 | >= 4.2, < 5.3 |
4.2 | 4-2-stable | >= 2.2.0 | >= 4.2, < 5.3 |
3 | 3-stable | >= 1.9.3 | >= 3.2, < 5.3 |
2 | rails2 | >= 1.9.3 | ~> 2.3.0 |
1 | ? | ? | ? |
Under SemVer, changes to dependencies do not require a major release.
Intellectual Property
Copyright (c) 2012 Ben Johnson of Binary Logic, released under the MIT license
Top Related Projects
Flexible authentication solution for Rails with Warden.
OmniAuth is a flexible authentication system utilizing Rack middleware.
Forms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.
Rails authentication with email & password.
Magical authentication for Rails 3 & 4
Authorization Gem for Ruby on Rails.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot