Build Node.js User Authentication - Password Login

Web Dev Simplified · Intermediate ·🔧 Backend Engineering ·7y ago

Key Takeaways

The video demonstrates how to build a secure Node.js user authentication system using Express and bcrypt, covering security concerns and password storage. It provides a step-by-step guide on initializing a Node.js project, installing required packages, setting up Express, and creating routes for user authentication.

Full Transcript

user authentication is crucial to every single website out there but it can be difficult to build a secure user authentication system so in today's video I'm going to walk you through all the cryptography and security steps you need to take to build your own login system using nodejs and if it's your first time around on this channel make sure you subscribe for more videos where I simplify the web for you to get started I just have a blank project open and the first thing we want to do is initialize it using NPM so we can tape an NPM an it and if we put - why it's just going to give us all the default values for a package.json and there you go you see it's created it for us and now the next thing we need to do is actually install the packages we're going to use for creating our Express server so we need Express which we're going to create our server with and we're also going to need bcrypt which is going to allow us to do all of our cryptography and securing of our passwords hashes after that's done installing we're going to install another package which is called node Mon which will allow us to restart our server automatically without having to manually crash our server and then restart it so we can just type in NPM I - - save dev node Mon and this is just a dev dependency because we only are going to be using this when we're developing our site and as I said isn't any time we make a change to our site it's going to automatically refresh our server for us so we don't have to do that manually and once that's done being downloaded we're going to create a script that's going to allow us to start our server using node Mun so to do that we can just come in here create a script called dev start and we just want to set that equal to here node Mon and we're gonna call server J s which is the file we're gonna save our server into and we can remove this test script since we're not going to use that now we can close out as package.json and create that server dot JS file just like this and in here we actually want to setup Express so we're going to get expressed first by saying Const Express is equal to require Express this is going to pull in the Express library and we want to get the app for that so we're going to stay constant app is equal to running that Express function next we can just say app dot listen on port 3000 and then just save that and we can run NPM run dev start and that's going to start up our server on port 3000 but it's not going to do anything because we don't have any routes set up so let's create our very first route we're going to create a route here what you're gonna be apt-get this is we're getting all of our users and when you create a real application you're not going to want to have a route that exposes your users password information but for testing purposes and to show you how this works we're going to create this users route so it's just going to be as slash users and it's going to come in here with a request and a response and all we're gonna do is we just want to send that users so we're going to say response JSON and we want to send our users so let's create a users variable for we're going to store our users in a real application you would most likely want to store this in a database somewhere but for testing purposes just a local variable we just find now in order to actually test to make sure our API is working let's create a file over here we're just gonna call it request dot rest and I'm using a package which is over here it's called rest client and this allows me to make rest request inside the S code if you want you can use a package or application such as postman to make these requests outside of your IDE text editor but I prefer to do this in the text editor since it's easiest and what we want to do is we want to make it get repost which is going to be at localhost 3000 whoops 3000 there we go make sure it says slash slash and we want to go 3,000 users and we can just send this request here and you can see it's going to get an interior rave users because right now we have no users in our array and if we wanted to add something for example we added a user with the name of name and we rerun this send the request you'll see we get that user in our array so we know that this is working properly let's default this back to an empty array now with any form of user authentication system we need to have a way to create users so we're going to use a post request for that we'll say a post and we're going to post to slash users again we're going to get that request and the response and here as our function and in here we need to do all of our code for creating a user hashing the password that they sent to us and saving it inside of this variable here so let's go over and emulate what our response is going to look like we're just going to say post here HTTP / / localhost 3000 and we want to just post to users and of course we want to make sure that the content type here is going to be for JSON so we're going to say application slash JSON and essentially all we're going to do is we're going to pass a name so let's do a name here we're going to say Kyle for example and then we want to pass a password as well this is going to be in the password variable and we're just going to pass along the password of password just for testing purposes and essentially we're going to pass this to our server and we want to convert this into a user in our users variable here and now the first thing you may be thinking is why not just put that directly into the users so we could just say request body dot name whoops name so we can get a variable here user is going to be equal to the name just like this and the password is going to be the same thing request body dot password and now you may be thinking that's perfectly fine this is going to work we can just say users dot push user and we want to make sure that we're actually able to accept JSON so we can just say app dot use Express dot whoops sometimes JSON just like this this will allow our application to accept JSON and then we just want to save res dot status whoops status set that equal to 201 and just sent a blank response back down to the user now if we come over here and test this you're gonna see it says it was created sent us a blank response and if we check all of our users you see that our users being saved here but the problem is is our password here is stored in plain text if anyone gets access to our database in any way they have all of the passwords and usernames for every single user in our database and we definitely don't want that we want to make sure that our passwords are hashed so that even if someone gets access to our database they won't actually know what the users passwords are this is where bcrypt comes in let's go back over to our server and require a V crypt so we're going to create a variable here B crypt whoops bcrypt and that's just going to be equal to require that library of decrypt just like this and to hash a password we need to have two steps we need to number one create a salt and then we need to use that salt along with the password to create a hashed password and the purpose of the salt is if we hash a normal password let's just say that we take the string here passwords we run it through some kind of algorithm we'll just say a function called hash just like this and that is going to respond and return to us something for example let's just say it returns to us a password that or a hashed password that looks like this now if we hash that exact same password later it's going to return to us the exact same string which means if multiple users have the same password they're going to have the exact same hash in our database which makes it easy if the potential malicious get access to our database and they cracked one password they're able to crack every other password that looks exactly the same and has the same hash so the way a salt works is we hash our password but what we do is we take some kind of salt and we add it to the beginning of our password before we hash it and this salt is different for every single user which means that when we hash our password it may look like this and then if we come down here and hash a new password we're gonna use a different salt and the hash for that password is going to look completely different even though the passwords are exactly the same this just makes it so that your database is more secure if someone gets access to it and they're not able to hash and break people's passwords because we have this salt and we just need to make sure we store this salt along with the password so when the user tries to log in we can use the same salt when we hash the password and luckily bcrypt takes care of all of this for us so let's just delete all this code here and we actually want to use bcrypt which is an asynchronous library so let's make sure we use an asynchronous function in here and we're going to use a try/catch and the first thing we want to do is we want to generate a salt so we're just going to say consult is going to be equal to be crypt Jen salt and it's just not going to take any parameters we can add it in around here by default this is going to be 10 and the larger you make this number the longer it's going to take to make the hash but the more secure it will be so for example at 10 we can generate a few hashes per second but if you bump this up to something like 20 or 30 it's going to take a few days to make one single hash I just like to leave this the default value so just completely leave it out of there and it'll generate a salt for us and since this is an asynchronous function we need to make sure that we await this and then we need to actually create our hashed password so we could say hashed password is going to be equal to again this isn't a synchronous function so we're going to await it and we just want to say decrypt hash and this is just going to take in our normal password which is request body dot password and then after that it's going to take the salt that we want to append to our hash and then we can just log that so let's do a console dot log of our salt and we're also going to console dot log our hashed password and now we're going to bring all this code up here inside of our try just like that and instead of saving our password as the normal plain text password we're going to save this as our hashed password just like that and the way bcrypt works is that actually going to save the salt inside the password so we don't need to separately say that we want to store the salt as well it already has that information inside the hashed password and then we just want to set a simple catch in here in case something goes wrong we can just set the status here equal to 500 and we can just send down nothing now let's save that and test that out if we go back over here we click post we're going to see that our salt is printed out right here and then we have our password which is this entire thing down here and you'll notice that the salt is at the very beginning of the password for every time that we encrypt it and that's how bcrypt is able to use just the hashed password to be able to compare the other version because it saves both the salt as you can see here at the beginning as well as the hashed password and if we run this again with the exact same password and we click send request you'll see we get a different salt which generates us a brand new different password at the end here and now to test that even further we can get a list of all of our users and you can see we have that hashed password being stored so even if someone gets access to our database they're not going to have direct access to the passwords and they're gonna have to crack them which is incredibly time-consuming and difficult to do so most likely they won't be able to get any information from us also bcrypt has a nice way of doing both generating the salt and hashing the password in one single step and we can just remove this salt section and in here instead of passing the salt we passed the number of rounds we want which by default is 10 so we're just going to pass in 10 here and that'll generate the salt for us without us having to do that first initial step let's remove these log statements save it and come back here and make sure everything's working so let's send a request to generate a user and we'll get that user and you can see it properly generated a user for us now they're able to store our user credentials let's take a look at how we would log in a particular user so let's just copy all this code up here paste it down here and essentially we're gonna do a post request again but we're gonna post two users slash login and we want to make sure we just pass along the name and the password because we want to check the person's name and then check to make sure that the password matches the password that they saved with us so let's actually create that route here come down here app dot post and we want to post users whoops slash users slash login and this is going to take in request and a response and we're again going to make this an asynchronous function because we're going to use bcrypt which is an asynchronous library to be able to compare our passwords now the first thing we need to do is get our user we can just create a variable here which is user and that's going to be equal to taking our users variable and we're trying to find a particular user based on the name we passed in so if the user dot name is equal to the request dot body that name then we know that we found a user from our initial list this is just matching out in the name and we can come in here and put a single if statement we just want to make sure that user actually exists so we'll say if the user is null then we're gonna send down an error to the user if we just say return res dot set status whoops status we want a 400 status and we want to send them down some text that says cannot find user there we go now let's set up our trycatch because this is where we're actually going to do the comparison for our password so we can set up our catch and the catch is going to do the same thing as they're catching the other one just return a 500 error and send nothing down to the user and inside of our tribe what we're going to use is we're going to use bcrypt dot compare and we're going to first pass it the initial password so request body dot password and then we want to pass it the hashed password so we can just say user that password which is our hashed version of the password and this is going to compare these two passwords it's going to make sure to get the salt out of this hash this initial password and make sure that both the hashed versions equal the exact same thing and we need to make sure we do this with bcrypt compare because it's going to be more secure because they're able to prevent timing attacks which is a certain type of attack that you can get hit with if you don't use bcrypt compare and constant timing algorithms which just takes care of for you so you don't even have to worry about it next we just want to await this and we want to just check if these are the same because it's going to return true or false for us so if the password is the same then we know our users logged in so we can just say res dot send success so we know that they're logged in and if for some reason this didn't work these passwords are not the same then we can just send something down here that says not allowed now that we have that all saved let's create a user so we can just send this post request and we can say here we have our user Kyle created and now let's try to log them in with a different password this is a different password so it should not work and if we send this you see we get an error saying that we're not allowed but if we type in the correct password and click send you see it's getting success because it's able to match these two passwords and that's all it takes to set up authentication if you want to see a more in-depth tutorial of me creating a full application built around up education let me know down in the comments below and make sure to check out my other videos where I simplify the web linked over here thank you very much for watching and have a good day

Original Description

In this video we are going to build a secure Node.js user authentication system. I will be covering all of the security concerns that you will run into while building an authentication system. We will also cover how to securely store a password in case of a database breach. Lastly, we will cover how to login a user securely based on their name and password. 📚 Materials/References: GitHub Code: https://github.com/WebDevSimplified/Nodejs-User-Authentication Login With Passport Tutorial: https://youtu.be/-RCnNyD0L-s 🧠 Concepts Covered: - What a password salt is - How to properly hash a password - How to store passwords - Basic express server setup - User login 🌎 Find Me Here: Patreon: https://www.patreon.com/WebDevSimplified Twitter: https://twitter.com/DevSimplified Discord: https://discord.gg/7StTjnR GitHub: https://github.com/WebDevSimplified CodePen: https://codepen.io/WebDevSimplified #WebDevelopment #WDS #JavaScript
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Web Dev Simplified · Web Dev Simplified · 0 of 60

← Previous Next →
1 Introduction to Web Development || Setup || Part 1
Introduction to Web Development || Setup || Part 1
Web Dev Simplified
2 Introduction to Web Development || Understanding the Web || Part 2
Introduction to Web Development || Understanding the Web || Part 2
Web Dev Simplified
3 Introduction to HTML || Your First Web Page || Part 1
Introduction to HTML || Your First Web Page || Part 1
Web Dev Simplified
4 Introduction to HTML || Basic HTML Elements || Part 2
Introduction to HTML || Basic HTML Elements || Part 2
Web Dev Simplified
5 Introduction to HTML || Advanced HTML Elements || Part 3
Introduction to HTML || Advanced HTML Elements || Part 3
Web Dev Simplified
6 Introduction to HTML || Links and Inputs || Part 4
Introduction to HTML || Links and Inputs || Part 4
Web Dev Simplified
7 Learn Git in 20 Minutes
Learn Git in 20 Minutes
Web Dev Simplified
8 5 Must Know Sites For Web Developers
5 Must Know Sites For Web Developers
Web Dev Simplified
9 10 Best Visual Studio Code Extensions
10 Best Visual Studio Code Extensions
Web Dev Simplified
10 Learn CSS in 20 Minutes
Learn CSS in 20 Minutes
Web Dev Simplified
11 How to Style a Modern Website (Part One)
How to Style a Modern Website (Part One)
Web Dev Simplified
12 How to Style a Modern Website (Part Two)
How to Style a Modern Website (Part Two)
Web Dev Simplified
13 3D Flip Button Tutorial
3D Flip Button Tutorial
Web Dev Simplified
14 How to Style a Modern Website (Part Three)
How to Style a Modern Website (Part Three)
Web Dev Simplified
15 Animated Loading Spinner Tutorial
Animated Loading Spinner Tutorial
Web Dev Simplified
16 How to Write the Perfect Developer Resume
How to Write the Perfect Developer Resume
Web Dev Simplified
17 Animated Text Reveal Tutorial
Animated Text Reveal Tutorial
Web Dev Simplified
18 Learn Flexbox in 15 Minutes
Learn Flexbox in 15 Minutes
Web Dev Simplified
19 Custom Checkbox Tutorial
Custom Checkbox Tutorial
Web Dev Simplified
20 Start Contributing to Open Source (Hacktoberfest)
Start Contributing to Open Source (Hacktoberfest)
Web Dev Simplified
21 JavaScript Shopping Cart Tutorial for Beginners
JavaScript Shopping Cart Tutorial for Beginners
Web Dev Simplified
22 Responsive Video Background Tutorial
Responsive Video Background Tutorial
Web Dev Simplified
23 1,000 Subscriber Giveaway
1,000 Subscriber Giveaway
Web Dev Simplified
24 How To Prevent The Most Common Cross Site Scripting Attack
How To Prevent The Most Common Cross Site Scripting Attack
Web Dev Simplified
25 Transparent Login Form Tutorial
Transparent Login Form Tutorial
Web Dev Simplified
26 The Forgotten CSS Position
The Forgotten CSS Position
Web Dev Simplified
27 How to Code a Card Matching Game
How to Code a Card Matching Game
Web Dev Simplified
28 10 Must Install Visual Studio Code Extensions
10 Must Install Visual Studio Code Extensions
Web Dev Simplified
29 Learn CSS Grid in 20 Minutes
Learn CSS Grid in 20 Minutes
Web Dev Simplified
30 Learn JSON in 10 Minutes
Learn JSON in 10 Minutes
Web Dev Simplified
31 10 Essential Keyboard Shortcuts For Programmers
10 Essential Keyboard Shortcuts For Programmers
Web Dev Simplified
32 What Is The Fastest Way To Load JavaScript
What Is The Fastest Way To Load JavaScript
Web Dev Simplified
33 Differences Between Var, Let, and Const
Differences Between Var, Let, and Const
Web Dev Simplified
34 How To Install MySQL (Server and Workbench)
How To Install MySQL (Server and Workbench)
Web Dev Simplified
35 Learn SQL In 60 Minutes
Learn SQL In 60 Minutes
Web Dev Simplified
36 How To Solve SQL Problems
How To Solve SQL Problems
Web Dev Simplified
37 What Are Design Patterns?
What Are Design Patterns?
Web Dev Simplified
38 Null Object Pattern - Design Patterns
Null Object Pattern - Design Patterns
Web Dev Simplified
39 Your First Node.js Web Server
Your First Node.js Web Server
Web Dev Simplified
40 How To Setup Payments With Node.js And Stripe
How To Setup Payments With Node.js And Stripe
Web Dev Simplified
41 How To Learn Any New Programming Skill Fast
How To Learn Any New Programming Skill Fast
Web Dev Simplified
42 Asynchronous Vs Synchronous Programming
Asynchronous Vs Synchronous Programming
Web Dev Simplified
43 JavaScript ES6 Arrow Functions Tutorial
JavaScript ES6 Arrow Functions Tutorial
Web Dev Simplified
44 Are You Too Old To Learn Programming?
Are You Too Old To Learn Programming?
Web Dev Simplified
45 JavaScript Cookies vs Local Storage vs Session Storage
JavaScript Cookies vs Local Storage vs Session Storage
Web Dev Simplified
46 JavaScript Promises In 10 Minutes
JavaScript Promises In 10 Minutes
Web Dev Simplified
47 Builder Pattern - Design Patterns
Builder Pattern - Design Patterns
Web Dev Simplified
48 JavaScript == VS ===
JavaScript == VS ===
Web Dev Simplified
49 JavaScript ES6 Modules
JavaScript ES6 Modules
Web Dev Simplified
50 8 Must Know JavaScript Array Methods
8 Must Know JavaScript Array Methods
Web Dev Simplified
51 CSS Variables Tutorial
CSS Variables Tutorial
Web Dev Simplified
52 JavaScript Async Await
JavaScript Async Await
Web Dev Simplified
53 How To Choose Your First Programming Language
How To Choose Your First Programming Language
Web Dev Simplified
54 Easiest Way To Work With Web Fonts
Easiest Way To Work With Web Fonts
Web Dev Simplified
55 Singleton Pattern - Design Patterns
Singleton Pattern - Design Patterns
Web Dev Simplified
56 Responsive Navbar Tutorial
Responsive Navbar Tutorial
Web Dev Simplified
57 CSS Progress Bar Tutorial
CSS Progress Bar Tutorial
Web Dev Simplified
58 Learn GraphQL In 40 Minutes
Learn GraphQL In 40 Minutes
Web Dev Simplified
59 What is an API?
What is an API?
Web Dev Simplified
60 Learn How To Build A Website In 1 Hour!
Learn How To Build A Website In 1 Hour!
Web Dev Simplified

This video teaches how to build a secure Node.js user authentication system using Express and bcrypt, covering security concerns and password storage. It provides a step-by-step guide on initializing a Node.js project, installing required packages, setting up Express, and creating routes for user authentication. By following this video, you can learn how to securely store passwords and compare them using bcrypt.

Key Takeaways
  1. Initialize a Node.js project using NPM
  2. Install Express and bcrypt packages
  3. Set up Express and create a route to get users
  4. Make a POST request to /users to add a new user
  5. Hash the password using bcrypt before storing it in the database
  6. Use Express to accept JSON requests and send responses back to the client
  7. Compare hashed passwords using bcrypt
💡 Using bcrypt to hash and compare passwords prevents timing attacks and ensures secure password storage.

Related Reads

Up next
Indian Express Editorial Analysis by Chandan Sharma - 1 JULY 2026 | UPSC Current Affairs 2026
StudyIQ IAS
Watch →