User Authentication with Bcrypt Password and JWT
Introduction
Welcome to the first lesson of our course, "Securing and Testing Your Ruby on Rails App." Today, we'll be focusing on user authentication, ensuring user passwords are stored securely using Bcrypt and managing authentication with JWT (JSON Web Tokens).
Authentication is a cornerstone of application security, protecting user data, and controlling access to specific parts of your app. Bcrypt is a proven library for securely hashing and storing passwords, making it computationally difficult for attackers to crack them. JWTs enable secure transmission of information as a JSON object, facilitating robust authentication management. By the end of this lesson, you'll be equipped to integrate JWT-based authentication in your Ruby on Rails app.
Let's dive right in!
Generating the User Model
First, we need to create a User model to store user information, including their securely hashed passwords. This model will encapsulate user-related data and behaviors.
Run the following Rails generator command to create the User model with username and password_digest fields:
Explanation:
- The
rails generate model User username:string password_digest:stringcommand creates a newUsermodel withusernameandpassword_digestattributes. - The
rails db:migratecommand applies the migration, creating theuserstable in the database with the specified attributes.
Securing User Passwords
With the User model in place, we'll add password hashing functionality using the has_secure_password method provided by Rails.
Open the user.rb model file (app/models/user.rb) and add the following:
Explanation:
class User < ApplicationRecord: Defines theUsermodel, inheriting fromApplicationRecord.has_secure_password: Uses metaprogramming to add functionalities for securely hashing and storing passwords. It automatically adds attributes likepasswordandpassword_confirmationto the model, managed in-memory for security purposes.
Now, whenever you create a new user, the has_secure_password method will ensure the password is hashed using Bcrypt and stored in the password_digest field.
