Authentication with Node.js and Express

The authentication is a very important part of almost any application. This post shows how to authenticate users on a Node.js server, using the Express, and storing the sessions with Redis.

Configuring the Session

Before we authenticate users, we must properly setup the Express sessions. Install theexpress_session package running the following command

After that, you must setup the installed package.

This way, the user session will be available on the req.session object.

Login

So, the login routine is shown below.

To access the POST data like above, you must use the body-parser package, and setup it

on the Express initialization routine.

Protecting the User Password

Much was already discussed about why encrypt the user passwords on the database. In short, if a malicious user gains access to the database, he, at least, will have a lot of work to recovery the original passwords if they were encrypted. This is important, since many people use the same password on every service.

To encrypt the passwords, I used the bcrypt package.

Also, is a good practice to use different salt strings for every user. This is due the fact that most people use common passwords, like 12345678 or password. So, if most of the users use some of these common passwords and a malicious user gains access to the database, it is not much hard to look for repeated passwords and test them against the most common used passwords.

In order to use bcrypt on Windows, i had to install the Visual Studio. You may download the free version here.

So, my login routine may be summarized on these steps:

  1. Check if there is any user with the informed e-mail;
  2. Get the salt string of this user;
  3. Encrypt the informed password with this salt;
  4. Check if the encrypted password matches with the one stored on database.

The implementation of these steps is

 

Leave a Reply

Your email address will not be published. Required fields are marked *