How to Set Up Basic Authentication in Rails

Authentication is an important aspect of web development and creating apps. You want to make sure that users can securely sign into an application, as well as ensure that their information is safe and not easily hacked. Fortunately with Rails, this is not overly difficult to achieve.

Creating Migrations and Models

This can be done by running rails new app_title. I ran — api because I am using Rails solely as a backend api.

Make sure to add the Bcrypt gem to your gemfile, it is needed in order for password encryption to work.

Next you need to create your migration and model for your users tables.

Running ‘rails g resource’ will generate a migration, model, and controller, all of which are important to set up authentication. After the migration has been created, run ‘rails db: migrate’ to generate a schema file and table for users. In the User model file, it’s important to add ‘has_secure_password’. The ‘has_secure_password’ method will encrypt passwords by hashing and salting them, then generating a ‘password_digest’.

For more information on hashing, salting and the encryption done by Bcrypt, check out this link:

Controllers and Routes

Inside of the UsersController is a create action that will create a new user entry in the database for the user that signed into the app, then store the ID inside of a session variable to persist that users status through page refreshes.

The user entry in the database is being created through the use of strong parameters. For more info on strong parameters, visit this link:

To authenticate users that are trying to log in ,a new route needs to be created.

This will send login requests to a new create action inside of the SessionsController. The create action in the controller will authenticate the user and either log them in, or return an error message.

The action should first query the database to find a user that matches the username of the person trying to log in. The conditional statement uses .authenticate() with a password that was given via params by the user logging in and checks whether it matches the password in the database. If it does, the user has been authenticated and that users information is now available to the frontend. If the password passed in does not match, an error is returned to the frontend.