Simple Authentication Guide with Ruby on Rails

Reinald Reynoso
Level Up Coding
Published in
7 min readOct 14, 2019

--

Photo by Jason Blackeye (Unsplash)

This is a simple tutorial on implementing authorization/authentication in your Rails application. I will be using the latest version (6.0) of Ruby on Rails. For the record, this is one of many ways to implement auth, and it is intended to showcase a basic approach.

Setup

We start off with generating a fresh Rails app.

rails new session_practice
cd session_practice

In the root of the directory, we will run a few commands to generate our models and controllers. Before we do so, let’s discuss the overall structure. We will be using one model, User. We will have two controllers, one for the User and one to handle custom routes to manage the session.

Model

Our user model will only have two attributes, username and password.

rails g model user username password_digest 

Controller

The UsersController will have the new and create routes. The SessionsController will have custom routes for login and welcome in addition to new and create routes. The view page for create will also be generated but will not be used, feel free to delete the file.

rails g controller users new create 
rails g controller sessions new create login welcome

Bcrypt

In our database, or any database for that matter, we should not store plain text passwords. Instead, we incorporate Bcrypt to encrypt the password and store it into the database. Let’s make sure we have the bcrypt gem installed:

gem install bcrypt
bundle install

For our User model, where we have the password field, we will set up a macro to utilize Bcrypt methods.

class User < ApplicationRecord     has_secure_passwordend

Routes

Next, let’s set up our routes under config/routes.rb. As you’re probably aware by now, routes already exist because we ran the rails g controller. We can remove those routes and add the ones we need.

Rails.application.routes.draw do   resources :users, only: [:new…

--

--