Integrate PassportJs Local Strategy into your Angular + NodeJs applications [MEAN stack]

Sai Kiran
3 min readAug 7, 2020

--

Passportjs is authentication middleware which can be used in application to login to your application. Passportjs has different types of authenticaction strategies to implement the authentications. We are discussing the ‘Local Strategy’ in this article. PassportJs has very impressive documentation which explains various examples of the authentication.

Let’s start with fronted part of the application. We are using Angular 8 as frontend framework and we are using reactive forms which sends the data to the backend.

Html File

I am login into my application using ‘username’ and ‘password’. You can configure your application to email and password if you want.

Ts file Part 1
Ts file part2

We are submitting the login data to the backend server. If the response is success we are navigating user to the next page. Or else we are displaying the error on the page.

Now let’s look into backend part of the application. PassportJs documentation mainly explains about the backend integrations. When the user submit the login form from the frontend. The backend api receives the username and password and verifies it with database. First, let’s Configure the passportJs to use the local strategy.

PassportJs configuration

PassportJs first search with with username if the username exists then it will verify the password using the verify password function. If both the values are true then it will return the user. Next writing the login api to login to the application.

Login Api

One of the main problem occurs to many people is how to create the User model to save the user details. So let’s look into the user model file.

User Model Part1
User Model Part2

In our application we have used ‘bcrypt’ to encrypt the password when the user submits the login form and store in the database. Whenever user updates the password it encrypts the new password and updates the hash password into the database. To install the ‘bcrypt’ use the following command.

For more information on bcrypt visit this site. https://www.npmjs.com/package/bcrypt

npm install bcrypt

To verify the password we are using the valid password function which check the password with the database by using the compareSync function which is available by the bcrypt modules.

This is basic implementation of passportJs Local Strategy into your Angular Nodejs application. I hope you find this article useful. If you have any queries in implementing the authentication. Feel free to reach me out saikiran1298@gmail.com

Thank you!!

--

--

Sai Kiran

Engineering @Walmart | Software Engineer & Technology Enthusiast