Understanding Authentication in Node.js - Sessions and Cookies - Web Development Concepts Explained

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi there what is up and welcome to another episode on concepts explained today's concept we're going to be looking at is authentication in node.js so what exactly is authentication authentication is the process of proving or showing something to be true or valid in this case we are checking to see if a user exists and if their credentials are valid so when it comes to authenticating a user on a website or in an application there are two main ways of handling it the first one being with the help of cookies and sessions and the second one will be using a signed encrypted token in today's episode we'll be exploring authentication using cookies and session so in order to understand how these two things can help us with authentication let's take a quick look at this diagrammed example first off we must understand how the http request and response cycle functions so http is a stateless protocol which means that there's a browser and there's a server and at the end of every request and response cycle the client and the server forget about each other and this is where sessions and cookies come in handy so this will work as follow we have our client and we have our server the client being our browser or our front end application and the server is our node application when the client makes a request to our server our server will automatically create a session and then store this session in the database when the server responds to the client it sends a cookie and this cookie is then saved in the browser this cookie will reference or point to the session that was stored in the database because this cookie will contain the session id and this cookie will then be sent for every consecutive request to the server so that the server will know who this browser or user is thus we have just made this connection stateful so so now that we understand this concept let's jump right into the code to show you how this will work in node.js so what i have here is just a basic express application i installed express and imported with the require function and then i initialized the express function in a variable called app this is all basic app.listen on port 5000 and then i just console.log the port and then i just have a basic route setup so the package we're going to use to help us create these sessions and set the cookies is called npm install express their session so what express that session does it basically sets the needed cookie for the specified session so this is used as follow we can after it's installed we can say const session you can name this what you want to i'm just calling it session and then express that session then we initialize a middleware with app.use and we pass it this session variable so this middleware will fire for every consecutive request to the server and this session receives an object and this object has a few options the first one being secret this is just the key that will sign the cookie so this secret takes in some key which is a string and this key will sign our cookie that is saved to the browser and then we have resave this we're going to set to false so this basic basically just means for every request to the server we want to create a new session even if we don't care about if it's the same user or browser and we don't want this so we set it to false and save uninitialized basically means if we have not touched or modified the session we don't want it to save and this is the only three we're going to use for now later we're going to use a store which will connect to our mongodb database to store the session in our database like we showed previously but for now i just want to show you that this middleware creates on our request body our request object it creates a session that we can view so if i save this and i run npm run dev i'm just using nodemon and i created a dev script to run the application i save this and i run and i go to this localhost 5000 i can see this session being logged out so what this piece of middleweight did is it set the start session to our request object so this request dot session will stay for any consecutive um request like i said before when a request and response cycle has ended there is no more communication or connection between the client and the server they completely forget about each other and what the session does is we can save data inside of our request dot session object that would be persistent through all of the request response cycles so if we go back to the browser and we open the developer tools and we go to application and then under cookies we can see that there is no cookie that pins that has been set yet and this is because of this uninitialized that we set to false so if i were to edit this session say i put a variable on this session called is off and i set this to true and i save this the application should restart and i refresh then you can see this cookie being set connect dot session id and it has some string this string was um signed by this secret we gave it now if i had to log go back to my code and log the session id console dot log request dot session dot id this session id will match up with the id in the cookie so this is how we tell the the server that this browser is using this specific specific session so let's check that out i'm going to save this i'm just going to restart this clear it up here i'm going to go to the browser and i'm going to refresh if we were to view this string right here we can see 9n8 and fbc and we go here we can check the string here it's 9 and 8 and fbc so that is the session id that is stored in the cookie so now that we understand what this package does for us let's jump right into creating our first get authentication project so now we want to save this session inside of our database so let's quickly set up our database i've got mongodb the local setup running in the background so in order to use mongodb i am going to use a package called mongoose npm iron mongoose so mongoose is just a object document model that just helps talk to mongodb as a database in a much elegant way so i'm going to import mongoose and require mongoose i'm just going to connect to mongodb with mongoose.connect and pass it the uri which is mongodb localist and like i said this is on my local environment and i'm going to call this database sessions and for mongod for mongoose not to complain we have to pass in three things use new url parser and set it to true use um create index and set it to true and the last one led to true typology and this will send a promise but for now we're not going to do anything with that so we just let it connect okay let's maybe use that promise then we don't care about the rest we just want to console.log mongodb connected okay with this our mongodb is connected so let's make sure that it works in p.m around there we can see mongodb is connected so this is working fine so now in order to save our sessions inside of this mongodb we are going to need another package if you go to the documentations on express session and we scroll all the way down we'll find options for storage and one of these options session storage implementations one of these there and there is a lot as you can see all these and one of them is connect mongodb right over here connect mongodb session so this session this package will allow us to save our sessions inside of mongodb so the setup is pretty simple and it works as follows so we import the package npm install connect connect db session with that installed we can now initialize it just below the session variable we can say const mongodb session we require it with connect mongodb session and then we pass it as a function and we pass it this session variable with that done now we can create a store and we're going to do this below the connection to mongodb we're going to say const store equals new db session and we pass in a few things here the first one being uri and this would be the exact same uris that we have up here so let's refactor that into a variable uri equals this string right here we paste that in there copy this and paste that in right there as well as right in there we give it a collection name and this collection name will just be a string that we set to my sessions and if i save this and pass this session variable down into the session middleware options where we have a store option and we pass that store right into it like so so with this setup it should work so let's go check it out i'm just going to make this smaller i'm going to run my script again npm around dev it all works fine i can go to my application and when i go into mongodb compass and i refresh i can see my sessions being created and inside my database sessions i have a collection of sessions there is no session created yet because we did not modify the session request so let's quickly do that in this route i'm going to say request.session dot is auth you can give it any variable i'm just using this auth as a example go back and refresh this when we go to our mongodb compass and refresh we can see now a session has been created inside of our database so now we have done everything for the process to work we have made a request to our server the server has created a session for that browser it has saved the session inside of the database and we send the cookie back and the cookie is saved inside of the browser so now all we have to do is connect the logic of authentication and use the session to help us so let's do that next so what i have done here is i have just set up a few ejs views and rendered them with these res render route so if we go take a look at our application it looks like this right now it really isn't pretty but it's just to drive the point home of how these sessions and cookies work so here is our landing page this is the landing page of the website i you have register and login button if i go to login i can enter my email i should just change that to password and my login button and then here i have email a username email and an email again i should just change that as well and then the page we're going to protect with authentication is this dashboard page so if you you're done signing in you will have access to this very top secret page and then it will have a logout button so let's quickly fix those small things let's go to the views it was on the login page we should have password right over here save this go back into the register we should have password here as well so with this all done let's start by creating the user model because we are going to add users to our database and authenticate them so let's start models and inside models we create a user file and here we're going to use mongoose once again so mongoose require mongoose i like to extract the schema of mongoose out of the mongoose schema like this you don't have to do it like this and then we create the user model user schema this would be of type new schema and it's an object that has username of type string and this will be required then we'll have an email field which is of type string as well and this will also be required this will also be unique because we won't allow people with the same email edges to register and then we have a password of type string and will also be required so once we set up our schema we have to export as a model so we can say mongoose.model and we give this model a name we call it user and then we pass it the user schema so now with our model set up for db we can import this model in our application so i'm going to say const user model is equal to require in our slash models slash user i have now access to all the crowd operations on this model so when i go to my register route on my register page that is load loaded through ejs i can see here this form has a wrong request i'm glad i saw this it should be slash register and a method of post and then from this form i will receive a username an email and a password so i have already set up the body parser in the middleware right over here app.use express url encoded so this will parse our bodies and give us access to the request.body so in my register post route so the app.post register i can now start my authentication process request dot body and i will pull out the username the email and the password so when we think about authentication when a user registers we want to check that this user does not exist in the database currently otherwise two people can't register with the same email so we're going to say let user equals and we're going to make this a asynchronous function to use async await and then we'll search in our database model dot find one who has this email and obviously we don't want this variable to have any user in otherwise that means it already exists so now we check if this user exists then we want to return to res redirect and go back to register so they have to try again so if this is not true then we will continue and now we will create our new user and we say new user model and you recreate that user we pass the username the email and the password but very important we do not want to save the string password directly into the database we want to encrypt that password before we save it so we are going to use a package called bcrypt.js so we're going to install that js and what this will allow us to do is encrypt our or hash our passwords so that they can't be changed or recognized by anyone so let's import this package const decrypt equals require decrypt js and how this will work is we get this password from our body so before we save or create this user we can say const hashed password and we set this equal to a weight because it returns a promise b crypt that variable that package we just imported and hash it has a hash function on it and this function accepts a string which is our password we want to hash and then we just pass it assault the salt will just make the hash more random so now we have this hashed password and we pass that hash password into our model when our model is done created we can now await user.save this is a mongoose method that saves this user we created into the database once we have finished creating created the user we can redirect to the login page so that the user now has to log in with their created credentials with that with this done let's check if it works go npm run dev no errors everything looks fine let's go to application let's go to register let's just close all of these up we don't need them now and here i can say my username is going to be lloyd email is going to be gmail.com and password is going to be password if i register now it should take me to the login page cannot register again a spelling mistake on my part i'll quickly fix that and now we press register it should it should take us to the login page and this has worked successfully if we go to mongodb compass and we refresh we can now see a user [Music] collection being created and this user was stored inside there with the hashed password so with this done let's work on the login the login is also fairly similar so we're going to extract from the body this body comes from if we go to our template we can see on our body we send a action to login and a method of post which is this route post login and on our inputs we have a email and a password so let's extract that email [Music] and password so firstly we want to check if this user exists so let's create a variable called user and on our weight so this has to be asynchronous function on our user model we search for find one with this email if this user does not exist you can't log in and then you have to redirect him to the login page or the register page for this one i'm just going to return dot redirect to slash login okay and if the user was found i want to compare the passwords so i'm going to create a variable is match and i'm going to wait and use this decrypt package again that has a compare method and on this compare method i pass the password i found from the body and then the password that is saved in the database which we found from this user we got from the database and let's see if this is not a match once again we want to return to the login screen return redirect slash login and if it is a match we want to log this user in so we will res dot redirect to slash dashboard and save so with this done let's test it out and go to back to the application with login with our email we just created in the database use the password which is password if we log in it should take us to the dashboard and we are officially signed in but this does not prevent the user from visiting slash dashboard even if they are not signed in so if i were to close my application and restart it and just go to slash dashboard i can still view it without logging in so we want to prevent this in order to do this we're going to use a piece of middleweight so let's do that let's go to our middleware section which is over here and i'm going to create a new variable is all this middleweight will contain request response and next and this middleware will check our request start session so when we're done logging in right over here before we redirect we want to save something on our session god is authenticated and set this to true now when we get to this piece of middleware which we're going to embed inside the dashboard it will check for that property so if request dot session dot is off so if that is true or so if it doesn't exist it's false but if it exists and is equal to true that would be true then we can call next else if that is not the case we want to res dot redirect to slash login so now we can pass this piece of middleware into our dashboard like this and so now we've passed this piece of middleware to this route so it will first check if uh where it will first check if the request is auth is set and then you will have access to this route so if i were to go back into our database i'm just going to clear the server restart if i were to go back into the database mongodb compass refresh this and delete this current session so on this session it will say is auth is true and i want to delete this and then make sure that on my initial routes i do not set anything except for when i am logged in so when i'm logged in it is the only place it would set this is auth so let's test it out now save this go back to our application if i were to which i'm not signed in right now i'm just going to delete this cookie which there's no cookie i'm going to try and visit the dashboard and it redirects me to the login page because i'm not yet signed in but if i were to sign in right now go to gmail.com password and login then i have access to this page and you can see the session cookie was created so now if i were to go back to the landing page and then go back to the dashboard i'm still authenticated so this cookie references to this session that was created in the database that says i am authenticated so now let's work on the login button and then we're basically done the login button will basically just remove the session from the database and there is a specific function on the express session package so we can go app.post and this will go to the log out on the dashboard view we can see that there is a form that has an action of logout with a method of post with that log out button submitting that form so we can trigger this request response and here we can say request dot session dot destroy and this destroy has a callback with an error and if there is an error we will throw that arrow which they shouldn't be and then we just want to rest.redirect to the landing page with this all set up let's go back to our application we can refresh we are still logged in because of this session id and if i log out it throws me back to the to the landing page you can see the cookie is still here but if we go back to the database and we refresh we can see the database is the database session is missing so now if i want to go to dashboard i would not be able to visit it although the cookie is still there this cookie doesn't point to anything in the database so it's basically null and void so now i have to re sign in and if i were to resign in gmail.com and password it would create a new cookie you can see the cookie has changed and i'm able to log in and view the dashboard so this is how authentication works in node.js using cookies and sessions i hope you enjoyed this video and felt found it helpful and if you did please remember to like and subscribe and leave a comment down below and i'll see you in the next one
Info
Channel: The Full Stack Junkie
Views: 29,225
Rating: 4.9672465 out of 5
Keywords: node js authentication session, understanding authentication in nodejs, login authentication in nodejs, login system in nodejs, authentication in web development, session authentication in express, nodejs authentication session, How does sessions work, Understanding sessions in web development, website authentication methods, using express session, javascript sessions, node authentication tutorial, login system node js mongodb, nodejs authentication
Id: TDe7DRYK8vU
Channel Id: undefined
Length: 30min 54sec (1854 seconds)
Published: Mon Aug 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.