The New Default. Your hub for building smart, fast, and sustainable AI software

See now
Ruby on Rails authentication and authorization with Devise and Pundit

Ruby on Rails Authentication and Authorization with Devise and Pundit (2026 Guide)

Patryk Gramatowski
|   Updated Nov 8, 2026

In a Ruby on Rails app, authentication checks who a user is, and authorization decides what that user is allowed to do. The most common way to handle both is Devise for authentication and Pundit for authorization. Together they give you sign-up, sign-in, password resets and per-action permission checks without building them from scratch. Since Rails 8, there's also a built-in authentication generator, so the first real decision is whether you need Devise at all. This guide helps you make that call, then walks through a working Devise and Pundit setup.

Executive Summary

Rails authentication and authorization are two separate layers. Authentication (Devise or the Rails 8 generator) proves identity, and authorization (Pundit) enforces what each identity can access. Getting the second layer wrong is the more common failure: broken access control is still the number one risk in the OWASP Top 10:2025. Devise is the faster route when you need sign-up, email confirmation, account locking or OAuth. The Rails 8 generator is enough for simpler apps where you're happy to write registration yourself. Whichever you pick, Pundit's policy classes keep permission rules in one testable place instead of scattering them across controllers.

What Is the Difference Between Authentication and Authorization in Rails?

Authentication answers "Who are you?", while authorization answers "What can you do?" The two are often conflated, but in a Rails app they live in different layers and usually different gems.

Image Source: Medium

According to OWASP, "Authentication is the process of verifying that an individual, entity, or website is who or what it claims to be by determining the validity of one or more authenticators (like passwords, fingerprints, or security tokens) that are used to back up this claim." In practice, it confirms a user's identity through credentials such as a password, a security token or biometric data.

For authorization, OWASP uses NIST's definition: "the process of verifying that a requested action or service is approved for a specific entity." It runs after authentication and determines whether a signed-in user may view a record, edit it or call a specific endpoint.

Why Do Authentication and Authorization Matter for Rails App Security?

Most real-world access problems are authorization bugs, not login bugs. In the OWASP Top 10:2025, broken access control holds the number one spot again, and OWASP reports that 100% of the applications tested had some form of it. A user who can open another customer's invoice by changing an ID in the URL has passed authentication perfectly. The failure is in authorization.

That's why it pays to treat the two layers separately. A mature authentication gem protects the sign-in flow, and a clear authorization layer makes every permission rule explicit, reviewable and testable.

Should You Use Devise or the Rails 8 Authentication Generator?

Use the Rails 8 generator when you need email-and-password sign-in and are fine writing the rest yourself. Use Devise when you need a full account system out of the box, which is common when building an MVP on a tight deadline. Rails 8.0 added bin/rails generate authentication, which creates a User and Session model, a sessions controller with built-in rate limiting, password reset and an Authentication concern. The Rails security guide is explicit that it doesn't generate sign-up, so registration is yours to build.

Rails 8 authentication generator

Devise 5

What you get

Sign-in, sign-out, password reset, session records, login rate limiting

Sign-up, sign-in, password reset, remember me, validations, plus opt-in confirmation, account locking, session timeout and OAuth via OmniAuth

What you build yourself

Registration, email confirmation, account locking, OAuth

Mostly customization of views and controllers

Code ownership

All the code lives in your app and is easy to read

Behavior lives in the gem and is configured through an initializer and modules

Best fit

Simple apps, internal tools, teams that want full control

Products that need a complete account system quickly

Neither option ships multi-factor authentication by default. With Devise, the usual route is a gem such as devise-two-factor. With the generator, you build it into your own code. Devise also has a learning curve: its own README recommends that developers building their first Rails app start with a simple authentication system from scratch instead.

The rest of this guide uses Devise. Pundit works with either option.

What Are Devise and Pundit, and What Does Each Gem Do?

Devise handles authentication and Pundit handles authorization. Between them, they cover the whole access-control flow of a typical Rails app.

Devise for Authentication in Ruby on Rails

Devise is a flexible, modular authentication solution for Rails. It's one of the most battle-tested gems in the ecosystem, with over 300 million downloads on RubyGems. The current major version, Devise 5, works with Rails 7 and later.

Devise is built from modules, so you enable only what you need. A newly generated model includes database authentication, registration, password recovery, "remember me" cookies and email and password validation. Email confirmation (confirmable), account locking after failed sign-in attempts (lockable), automatic sign-out after inactivity (timeoutable) and OAuth sign-in (omniauthable) are opt-in.

NOTE: Devise uses bcrypt for password hashing, and so does the Rails 8 generator. Why do I mention it? Because bcrypt has limitations, and if you rely on a tool, you should know the constraints of what it uses under the hood. The best known is that bcrypt only uses the first 72 bytes of a password. For details and mitigations, read More Secure Passwords in Bcrypt — Beating the 72 Bytes Limitation.

Pundit for Authorization in Ruby on Rails

Pundit is a lightweight authorization library that builds your permission rules from plain Ruby classes called policies. Each policy usually corresponds to a model, and each method in it answers one question, such as update? or show?, for a given user and record.

That design makes permissions granular and easy to test, because a policy is just a Ruby object you can unit-test without a browser. It also scales well: new rules mean new policy methods, not a growing tangle of if current_user.admin? checks in controllers and views.

Next comes the practical part: configuration and implementation.

How to Configure Devise for User Authentication in a Rails App

After the steps below, your Rails app will have a working sign-up and sign-in flow.

First, add Devise to your Gemfile:

# Gemfile

gem "devise"

You can check the latest version on RubyGems. Then run bundle install, followed by the install generator:

rails generate devise:install

The generator creates config/initializers/devise.rb, which lists all of Devise's configuration options, and prints a few setup instructions in the console. Read them and apply the ones that fit your app.

Our application isn't API-only, so we set the default URL options for the Devise mailer (recent Rails versions already include this line in new apps):

# config/environments/development.rb

config.action_mailer.default_url_options = { host: "localhost", port: 3000 }

To have something to protect, generate an example controller:

rails generate controller examples index show

Then point the root route to it:

# config/routes.rb

root "examples#index"

To see Devise's success and error messages, render the flash in your layout:

<!-- app/views/layouts/application.html.erb -->

<body>
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
  <%= yield %>
</body>

How to Generate a User Model with Devise in Ruby on Rails

Now you can add Devise to a model. It's usually User, but it could also be Admin, Member or anything else:

rails generate devise User

This creates the model and a migration, and adds devise_for :users to your routes. By default, the model includes these modules:

  • Database Authenticatable: hashes and stores a password in the database to validate a user's identity during sign-in. Authentication can happen through POST requests or HTTP Basic Authentication.

  • Registerable: handles sign-up and lets users edit and delete their accounts.

  • Recoverable: resets the user's password and sends reset instructions.

  • Rememberable: generates and clears a token for remembering the user from a saved cookie.

  • Validatable: validates email and password. It's optional and can be customized.

You can find all available modules in the Devise documentation on RubyDoc. If you enable an opt-in module such as confirmable or lockable, uncomment the matching columns in the migration before running it.

Next, run the migration:

rails db:migrate

To test the flow, add a sign-in link to the example view:

<!-- app/views/examples/index.html.erb -->

<h1>Examples#index</h1>
<%= link_to "Sign in", new_user_session_path %>

Your authentication mechanism should look like the screenshots below:

To require sign-in for a whole controller, add Devise's helper as a before_action:

before_action :authenticate_user!

In this example, we skip it on purpose, so the Pundit policy below can decide what anonymous users may see.

How to Customize Devise Views for Your Rails App

To change the look of the sign-up, sign-in or any other Devise form, copy the views into your app:

rails generate devise:views

This creates them in app/views/devise, where you can edit them like any other view.

How to Add Authorization to Ruby on Rails with Pundit

To add Pundit, add the gem, include its module in your application controller, and decide what happens when access is denied.

Add the following line to your Gemfile:

# Gemfile

gem "pundit"

You can check the latest version on RubyGems. Then run bundle install and include Pundit::Authorization in your application controller:

# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit::Authorization
end

Optionally, run the generator. It creates an ApplicationPolicy with useful defaults in app/policies, and you should restart the server afterward:

rails g pundit:install

When a policy denies access, Pundit raises Pundit::NotAuthorizedError. Without a handler, users see an error page, so rescue it in your application controller. It's also worth adding verify_authorized, which raises an error whenever an action forgets to call authorize. We skip it for Devise's own controllers, which don't use Pundit:

# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit::Authorization

  after_action :verify_authorized, unless: :devise_controller?
  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def user_not_authorized
    flash[:alert] = "You are not authorized to perform this action."
    redirect_back_or_to(root_path)
  end
end

Step-by-Step Guide to Writing Authorization Policies with Pundit

Now you can create your own policies. In our case, we'll write a policy for the ExamplesController created for the authentication mechanism:

# app/policies/example_policy.rb

class ExamplePolicy
  attr_reader :user, :example_object

  def initialize(user, example_object)
    @user = user
    @example_object = example_object
  end

  def index?
    true
  end

  def show?
    user&.created_at&.today? && example_object[:show] == true
  end
end

Here's what each part of the policy does, starting with the initializer:

def initialize(user, example_object)
  @user = user
  @example_object = example_object
end
  • The first argument is the user. In your controller, Pundit calls the current_user method (provided by Devise) to get it.

  • The second argument is the record whose authorization you want to check. It's usually a model instance, but it doesn't have to be an ActiveRecord object.

Here, you allow any user, even one who isn't signed in, to access the page:

def index?
  true
end

Here, only signed-in users whose accounts were created today get access, and only when the show key in example_object is true:

def show?
  user&.created_at&.today? && example_object[:show] == true
end

NOTE: In our case, example_object is neither an ActiveRecord nor an ActiveRecord::Relation instance, but a simple hash.

Now let's call the policy from the controller:

# app/controllers/examples_controller.rb

class ExamplesController < ApplicationController
  def index
    authorize Hash, policy_class: ExamplePolicy
  end

  def show
    example_object = { show: true }

    authorize example_object, policy_class: ExamplePolicy
  end
end

To keep the example simple, example_object is a hardcoded hash. In a real app, it would usually be a model instance, such as authorize @invoice. Then Pundit infers the policy from the class name and you don't need policy_class. We pass policy_class: ExamplePolicy because, without it, Pundit would look for a HashPolicy, since our record is an instance of the Hash class.

If a user who signed up before today opens the show page, show? returns false. Pundit raises Pundit::NotAuthorizedError, and the rescue_from handler redirects them with an alert.

Key Takeaways

  • Authentication proves who a user is. Authorization decides what they can do, and it's where most access bugs happen.

  • Broken access control is the number one risk in the OWASP Top 10:2025.

  • The Rails 8 generator covers sign-in and password reset, but you build sign-up yourself. Devise gives you a full account system out of the box.

  • Pundit keeps permission rules in plain Ruby policy classes that are easy to test.

  • Add verify_authorized and a rescue_from handler so missing or denied checks never fail silently.

How Do Devise and Pundit Keep a Rails App Secure as It Grows?

Devise and Pundit give a Rails app a solid access-control foundation: a proven sign-in flow and permission rules that live in one testable place. Long-term success depends less on the initial setup than on the habits around it. Every new action needs an authorize call, every new role needs policy tests, and the gems need regular upgrades, because Devise alone shipped two security fixes in the first half of 2026. To explore further options, review the Devise and Pundit documentation.

If you'd rather have experienced Rails engineers design or review your authentication and authorization, Monterail's Ruby on Rails team can help. Our work ranges from security-focused code reviews to preparing a Rails platform for enterprise security audits. You can also learn more about working with a Ruby on Rails agency.

Rails Authentication and Authorization FAQ

Patryk Gramatowski avatar.
Patryk Gramatowski
Ruby on Rails Developer
Linkedin
Patryk Gramatowski is a detail-oriented software engineer with extensive experience in designing and developing dynamic, high-performance web apps with Ruby, Ruby on Rails, and other technologies. He’s deeply committed to building secure, scalable, and maintainable software solutions that meet technical and business objectives.