Rails Authentication

Rachel Emmer
The Startup
Published in
2 min readOct 26, 2020

--

rubyonrails.org

Implementing authentication into your Rails application makes your project user friendly and sophisticated. Mastering authentication is a major milestone for aspiring developers and is a great way to test your programming skills.

To begin, create a new Rails application. You’ll need to comment in the gem bcrypt and run bundle install. Check your Gemfile for bcrypt and its corresponding version to ensure it was installed successfully.

gem 'bcrypt', '~> 3.1.7'

Next run rails g resource user to create your user routes, controller, and model. You’ll need to add a create action in your user controller to be able to create new users.

class UsersController < ApplicationController
def create
@user = User.create(
username: params[:username],
password: params[:password]
)
render json: @user
end
end

In your routes.rb file, only allow the create method.

resources :users, only: :create

In the user model, add the has_secure_password method to encrypt your user’s password.

class User < ApplicationRecord
has_secure_password
end

In your migration file, make sure to add the strings username and password_digest as your user attributes. Password_digest ensures that the encrypted password is stored in the database, not the plaintext password.

class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :username
t.string :password_digest
t.timestamps
end
end
end

Finally, run your migration. To test if you were successful, try to create a new user in Postman. If you were able to, congrats! Now it’s time to implement the code to allow your user to log in.

First, create an authentication controller. To do so, run rails g controller authentication. Then add the following code to create your login method. This is looking up your user and authenticating them.

class AuthenticationController < ApplicationController
def login
@user = User.find_by(username: params[:username])
if !@user
render json: { error: "Wrong Username" }
else
if !@user.authenticate(params[:password])
render json: { error: "Wrong Password" }
else
payload = { user_id: @user.id }
secret = Rails.application.secret_key_base
token = JWT.encode(payload, secret)
render json: { token: token }
end
end
end
end

Next, add a login route to your routes.rb file. This is sending a post request to the login action in your authentication controller.

post "login", to: "authentication#login"

Finally, add the gem ‘jwt’ to your Gemfile and run bundle install. JWT stands for JSON web token and provides your user with a token so they don’t have to continually log in every time they complete an action on your application. In Postman, send a post request with your username and password to your login route to test if you get a token in response. If so, you’ve successfully implemented authentication into your application!

--

--