Devise Authentication Deep — Advanced User Authentication
In this tutorial, you will learn about Devise Authentication Deep. We cover key concepts, practical examples, and best practices to help you master this topic.
Devise provides flexible authentication with modular strategies including database authenticatable, confirmable, lockable, timeoutable, trackable, and OmniAuth integration.
What You'll Learn
By the end of this tutorial, you'll configure Devise modules, customize authentication strategies, implement OmniAuth, handle API token auth, and customize Devise views and controllers.
Why Devise Matters
Devise handles authentication with battle-tested modules. Its modular architecture allows picking only needed features, from basic password auth to OAuth providers.
Real-World Use
A SaaS platform uses Devise with database_authenticatable, confirmable for email verification, lockable for brute force protection, and OmniAuth for Google and GitHub login.
Devise Path
flowchart LR
A[Authentication] --> B[Devise Deep]
B --> C[Modules]
B --> D[OmniAuth]
B --> E[API Tokens]
B --> F[Custom Views]
B --> G{You Are Here}
style G fill:#f90,color:#fff
Devise Modules
Configure Devise modules in the User model.
class User < ApplicationRecord
devise :database_authenticatable,
:registerable,
:confirmable,
:recoverable,
:rememberable,
:trackable,
:lockable,
:timeoutable,
:validatable
# Customize lockable
self.lock_strategy = :failed_attempts
self.unlock_keys = [:email]
self.unlock_strategy = :email
self.maximum_attempts = 5
self.unlock_in = 30.minutes
# Customize timeoutable
self.timeout_in = 2.hours
end
Custom Strong Parameters
Permit custom parameters in Devise.
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [
:name, :username, :terms_accepted
])
devise_parameter_sanitizer.permit(:account_update, keys: [
:name, :username, :bio, :avatar, :notification_preferences
])
end
end
OmniAuth Integration
Add social login with OmniAuth.
# config/initializers/devise.rb
config.omniauth :google_oauth2,
Rails.application.credentials.dig(:google, :client_id),
Rails.application.credentials.dig(:google, :client_secret)
config.omniauth :github,
Rails.application.credentials.dig(:github, :client_id),
Rails.application.credentials.dig(:github, :client_secret)
# app/models/user.rb
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0, 20]
user.name = auth.info.name
user.skip_confirmation!
end
end
API Token Authentication
Authenticate API requests with tokens.
class User < ApplicationRecord
devise :database_authenticatable, :registerable
has_secure_token :api_token
end
class Api::V1::BaseController < ApplicationController
before_action :authenticate_api_user!
private
def authenticate_api_user!
token = request.headers["Authorization"]&.split(" ")&.last
@current_user = User.find_by(api_token: token)
render json: { error: "Unauthorized" }, status: :unauthorized unless @current_user
end
end
Common Mistakes
1. Not Customizing Devise Views
Default Devise views look generic. Customize templates for brand consistency.
2. Missing Email Configuration Without Confirmable
Devise sends confirmation emails. Configure mailer settings or disable confirmable.
3. Not Using Strong Parameters for Custom Fields
Custom fields are rejected by Devise parameter sanitizer. Always add custom keys.
4. OmniAuth Without Callback Handling
OmniAuth callbacks must handle both success and failure paths.
5. Not Securing API Tokens
API tokens are sensitive. Use HTTPS and allow token rotation.
Practice Questions
1. What Devise module locks accounts after failed attempts?
lockable module.
2. How do you add custom fields to Devise registration?
Use devise_parameter_sanitizer.permit(:sign_up, keys: [:custom_field]).
3. What does confirmable do?
Requires users to confirm their email address before accessing the app.
4. How do you integrate social login in Devise?
Use OmniAuth Strategy in initializer and from_omniauth method in User model.
5. Challenge: Configure Devise with OmniAuth and API tokens.
class User < ApplicationRecord
devise :database_authenticatable, :registerable, :confirmable, :lockable
has_secure_token :api_token
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token
user.skip_confirmation!
end
end
end
FAQ
Mini Project: Full Authentication Setup
Configure Devise with all common modules.
# config/initializers/devise.rb
Devise.setup do |config|
config.mailer_sender = "noreply@example.com"
config.mailer = "Devise::Mailer"
config.parent_mailer = "ActionMailer::Base"
config.case_insensitive_keys = [:email]
config.strip_whitespace_keys = [:email]
config.skip_session_storage = [:http_auth]
config.stretches = Rails.env.test? ? 1 : 12
config.reconfirmable = true
config.expire_all_remember_me_on_sign_out = true
config.password_length = 8..128
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
config.timeout_in = 2.hours
config.lock_strategy = :failed_attempts
config.unlock_strategy = :email
config.maximum_attempts = 5
config.unlock_in = 30.minutes
config.last_attempt_warning = true
config.reset_password_within = 6.hours
config.sign_out_via = :delete
end
What's Next
Rails Cancancan Rails API Mode Rails Serializers
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro