Authentication using JWT Token: Node Js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay then hello hello hello everyone good evening guys good evening subashini tarun sham Drex Nanda utpal good evening guys good evening positive good evening stay safe so your names are amazing so good evening guys good evening everyone can you please confirm am I audible am I visible to you guys can you please confirm that once okay hopefully we are live okay that's great so yep guys good evening even good evening good evening everyone and I welcome you all to day seven of this nodejs master class so guys today is day seven or you can also see the second last day of this course okay good evening ainka good evening buddy seeing you after a long time how are you okay so guys as I was saying today is the second last day of this course and so far we have learned so much and first of all on the second last day I would like to thank you all from my heart for joining every single day and making this particular course this big okay so all of you joined I can remember your names all of you joined every day and right now who are not here thank you to everyone for joining the course and guys today second last day and we are going to be learning something really very important which is called as authentication and authorization one of the most important things in application development or web development scenario one of the most important things now why it is important what exactly is authentication what exactly is authorization and and you can also see in the title I have mentioned something called as JWT token again one of the very important Concepts in API development so we'll be learning all that but before that let's just do a quick revision of what we have learned so far and you know just let's just recall all those things so guys so far we have understood what exactly is a API right how an application is made what part an API plays in the whole application development process what exactly is the API server what is request what is response we have learned all that stuff we have understood how many different kind of requests we can send what exactly is a request URL right we have learned all that stuff we have also learned how to send responses what exactly is a status code we have also learned what exactly is a header right and we have seen how to handle all that stuff from the core because initially we used something called as HTTP module to create our first API in that we didn't have a real-time database we used a file system as our database but we understood from the core we understood that if a request comes on this URL with this method how to handle it if the request comes on products URL with post method how to handle it how to handle get method what exactly is the meaning of course right how to handle course issue so we have seen all that stuff and then yesterday by learning all that stuff from previous 5 days yesterday on day six we learned Express a library which makes API development API creation much more easier it's a library built on top of HTTP module which gives you a lot of functionalities so that you don't have to write everything from scratch but we also learned it how to write things from scratch and yesterday we learned how to use express module and use its functionalities to handle all different kind of request handling URL parameters right and also we connected it to database and we sent the responses of the data coming from database so overall we built a really cool API right guys so this is what we have done so far and today's session is completely going to be about authentic tication authorization and something called as jwd token which I'll be introducing you in some time don't worry about that today's session is all about that and how to give security to your API see guys the main concept for today is how to make your API secure see now yesterday we created API right so it's working but the problem with our API is anyone with the proper URL and proper method anyone who knows my server URL see right now it's a local server so it's okay like no one can from America can access my server because it's a local server but what if I launch my API to a server to a real server which all the world can access in that case my API If someone knows my IP address or my domain name and proper port number and proper routes anyone can access my API literally anyone and that's fine if I want to keep my API public that's okay so guys yesterday whatever API we created it's public that means anyone with the proper URL can access my API even if I launch it on a server it can still be accessed so because it's public but it's up to us if needed we can make our API private or we can make our API much more secured so that normally people won't be able to access my API directly if they want to access they can log to my API they can put a username password just like flipcart see just like you go on applications like flipcart Amazon right you cannot buy products until you login some sites tell you that no first login then only you can do something like Facebook there without login you cannot do even one thing first register and login then only you can do something now sites like Flipkart Amazon they let you see the products they let you explore the features and then only while buying you have to log in so some sites they give you everything once you log in right some sites give you few features by default like okay fine these are public you can access them but only if you want to buy or you know add to card or something like that you have to log in so it's like that so it depends on you it depends on your project what kind of security you want do you want your whole API to be public do you only want some AP some parts of your API to be public that can be accessed normally and some parts to be secured right so it's up to us and today we'll be learning all that is that clear guys that is the concept of API today so what we'll be doing is we'll be creating a feature where the user has to login First so before login he will register that means if someone so let's say on my API I have around 20 end points right let's say one end point is giving products one end point is uh giving single product one Endo is for creation of product one endpoint is for deletion of product let's say out of that let's say viewing products I want to do public so that's fine anyone can call it but creation and deletion should be only done by valid user so for that I will ask the user first okay first please login so that I can know that you're a valid user of my company or you're you're an admin or something like that so that is what we want to achieve today either full security or partial security it depends on your features but again let's learn the basics of that and then you can decide what you want to do so guys there are two important Concepts regarding the security that is authentication and authorization so let's try to understand these two terms first and then we'll move ahead and start creating the services or the API okay so let's remove this first let's try to understand what exactly is authentication and I think everyone knows it because nowadays in this Digital World everyone is loging somewhere or creating account somewhere so I think everyone knows what exactly authentication is but again let's discuss it so guys authentication simply means letting the server or letting someone know who you are so let's say I go on Facebook right so I register myself I put my username password email date of birth and all that and now to log in I go ahead and put my username and password and I click on submit so now the Facebook will check if this user username and password is correct by doing that Facebook is checking if this user is actually valid to use my services to use my Facebook Services that's what Facebook is checking that is what you call as authentication checking if a user is valid so checking if a user is valid that is what meaning of authentication simple on Amazon also you see your products now you want to add to cart so you click on login now it will ask you please put your username password right and it will check if your username password is correct if you're a proper user of this particular website then only I'll let you use the other features so checking someone if he or she is valid or not that is what you call as authentication and that is the primary part before you want to do anything first prove that you're a valid user that is authentication is that clear guys and don't worry in some time I'll also discuss authorization I don't want want to bombard everything on your head right now so let's go step by step let's go step by step so let me go ahead and quickly create a new folder see guys again don't worry I'm not going to give you all the concepts as once we'll go step by step whenever the authorization will be needed then I'll explain you so you'll understand it better so don't worry now then let's go on and let's do this concept first okay because and see guys how the concept works even if you want to log in the first thing is you have to register now sometimes you know some users are inter inter that means you won't even have to register internally the admin people or the company people will create your account like Banks you don't go and register on their site right normally what happens you fill a form you submit it to them they create your account internally so it might also happen they might also create an account internally that means registration can be done anywhere directly by the employees in the database or they will give your a form on the website which you can fill or like Facebook you can fill your form and then click on create account so that that is what we call As registration in our case what we will do is we will create one endpoint from where user can register so let's say we are building an API think of it guys let's actually you know build a idea let's say we are creating uh something like you know let's use the uh old concept only our old concept that we created the API last time right so what we will do is we'll create a concept and the concept is let me open the API first before doing anything let me quickly open the API wait yes yesterday we created API right let me quickly open that so let's say my API is a Inventory management system or something like a product management system so we created this API yesterday right so this is a product management system API which has features like fetching all the products right then fetching a single product whenever needed then creating a product then deleting a product and then updating a product so let's say this is a inventory management system API but what I want is right now all these endpoints are public I don't want that what I want is if you want to use my endpoints if you as a user or any user wants to use my endpoint first register to my API and then login and then only you're allowed first register and then login okay that is the concept so first of all let's quickly go and let's perform authentication after that we'll move on to authorization and tokens first let's do the basic stuff so guys now I have to do is now user will register so if user register I also want to store them somewhere correct guys I also have to store them somewhere right so let's go for that we'll again go in our mongodb compass and we'll create a new collection where I'll be storing my users because I already have a product collection in which all my products are stored that is simply for creating updating deleting products that collection I need one more collection where I'll be storing my users now because users will register first so let's go and let's build all the features together so okay I already have one users collection let me delete that I don't want it let me remove all the extra stuff that we don't need drop collection and also drop this collection as well so name is users drop and now let me create one more collection and we'll call it as users because the first thing I want to do is registration okay done now we know that everything else is done on the API side so guys let's push this down let's put this down let's put all these end points down or all the features related to products down here okay so coding something like related to products let's leave it down here okay fine uh so it's like creating a function that is called first then we check condition exactly rishikesh exactly same like Facebook right first they give you a form fill it only if you're a valid user then I'll let you go inside same on the apis you don't want anyone to use your apis so first register yourself on my API now again as I said registration can be done in any way that is different but login is important and for login I need to know the user that's why registration is important then you perform login only if you're valid then I'll let you access all the other end points by default you won't be able to access that's what we want to do here is that clear guys so first authenticate then only allow cleared guys everyone so let's go so now see mongodb connection is here all good okay and then after that whatever is related to products schema model everything I'm putting it down let's leave it there and now let's work here on users okay so here it is coding related to users Okay cool so first of all schema for users let's go const user schema do schema and then simply only few things guys we don't need a lot of things only few things so let's go schema utpal is simply a set of rules and regulations of how your data your record or your document should look like that's all schema is simply a way of representing how you data will look like so I have created a product schema here that means whatever product you're trying to insert or update in my database it should at least have name price quantity category property these are the four properties it should have and these are the rules all those properties should follow so it is basically a representation of your data how your data should look like structure of your data that's it that's what a schema is so here I'm creating a user schema that means whenever you're planning to insert user because now users will register right so they're going to be inserting data in database so while inserting data in database how the user data should look like that's what I'm mentioning here okay so user should have a name so that's why name and then username will be string okay and you can also mention required here you know so required true and eror message like name is mandatory okay simple and then after that you can have have one password field sorry my bad password field and then again this will be also of type string and also required so I'm going just going to take this password is mandatory and one more field actually I'm going to call it as username or email you can also use email as the username right so let's have email here email something like that okay and email is mandatory simple type spelling where ah yeah sorry I got it thank you and then after this here we'll also have timestamps true that's all so that every time a record is created there will be time stamps Hi naven how are you buddy after a long time you're here how are you I hope everything is good so guys user schema is created right because right now we working on registering the user okay so schema is done now let's quickly create the model so model for user Okay cool so now guys quickly create the model so const user model equals dot guys I hope now everyone is familiar with this right there's no confusion in doing all these stuff hopefully so our collection is users and our schema that I want this model to follow is user schema that's all and now let's create an endp point to create a user okay everyone let's go and point to create a user or new user something like that okay so guys it's for creation so you tell me post or get or put or patch which one it will be come on I'm not even keeping delete an option I hope no one will give give that answer it's for creation of a user so guys post get put what what it what should it be exactly post nice so app dot post okay and then it should be called on/ users something like that and here request response okay cool and now I'm also thinking should I continue the whole thing in this project or should I create a new project for this what what what do you guys say everyone what do you guys say should I continue in this project only or should I create a new project what do you guys say I'm thinking I'm thinking like it will not be complicated but just thinking what do you guys say should I create a new project what say quickly quickly tell me because we have just started we can still copy and paste stuff from here so quickly tell me new let's do it let's do it let's do it I thought of it initially but I thought that we have already done yesterday a project so let's do that but okay just to give you idea I came to this project but now let's go back this was just for giving you the idea so let's do one thing let's go in our folder okay and let's create a new folder and let's simply call it as Au because we are only learning authentication here so let's call it AU let's put it here and now let's start a new okay cool and then let's create a new database as well why not let's call this database as Au demo something like that okay but you got the idea right why do we need authentication guys everyone what are we trying to do here we don't want anyone to directly access our endpoint so we are creating authentication process where they have to register and login just like Facebook or Amazon but that is authentic on websites here we are doing it in the API but at the end it will be done from the front end so yeah okay and let's call it as users okay cool let's go then quickly so let's do the basic project setup guys now see guys I'm showing you one way of installing all the libraries at once you can do npm install now we know what we need we need Express so Express space we need so space space what else do we need guys do we need anything else no not now so yeah that's fine Express space if you need anything else space space you can just go on like that and that should be it okay cool settled everything settled and yeah I forgot doing npm in it but don't worry the basic idea is done so no issues you can also do npm in it afterwards so this file will be updated so npm in it yes or done done done done an author I'll put my name no issues here we go done okay yes I I didn't see yes done see the file has been updated now so no issues you can also do it afterwards after installing the things node Monon is installed globally Nanda don't worry node moon is installed globally now guys see before we move ahead in the coding part actually I want to do something wait wait wait see right now what are we doing exactly I want to explain you that now I have already explained it but just to give you a whole idea what exactly we are doing I'm going to explain it again once okay see so now right now what's happening in our case we might have a front end application or we might have a testing client correct this is my front end area either a application or a testing client so let me mention it this can be your frontend app or it can also be your testing client okay anyone it can be and let's say this is my backend server in which I have different different API endpoints let's say this is Facebook just to give you idea let's say this is Facebook okay so this is endpoint for registering new user so this is let me mention guys please understand here you'll understand everything because I know some confusions are always there so this is for registration okay this is for login this is for let's say you know something like um what can we call it registration login let's say this is for create post and this is for delete post something like that okay basic idea now understand see why I'm doing this because you know sometimes people get confused in front end and back end that means now if a testing client or or a front end app doesn't matter if a testing client or a front- end app if they want to perform create post operation or if they want to perform delete post operation the first thing that they should do is login right the first thing that they should do is login now if a testing client is doing it that means people will open the testing client directly fill data and click on submit correct send request and if it is actual front-end app people will be having a form which they will fill right getting the idea guys if it is a testing client people will open the client directly fill all the data and click on send request that we using so far and if it is actually a front-end app there they will be having form login form where they will fill data click on submit and some code will send the request to login but again before login login is only possible if you are already a user that means first thing that they have to do is registration and then they can perform login and only if they are logged in users then only I'm going to allow them to perform create post and delete post now just remember this this is what we are trying to achieve okay everyone this is what we are trying to achieve now let's go just wanted to give you one now I know we have understood it just wanted to give you one extra line of explanation once more because there is one very important thing going on here so please understand we'll come back to that afterwards we'll not make it tough right now okay focus guys so let's go so first thing is we'll create a new file let's call it as index. JS quickly require all the basic things and guys if anyone is new remember guys this is day seven of this course so there are a lot of things that we have learned so far so if you don't understand some things going on today please watch my previous sessions as well they will help you a lot so guys first of all Express okay then we'll go ahead with what done with now that's cool and now first thing database connection okay because that is going to be used in my whole application so quickly go ahead do connect my URL is going to be mongodb col slash Local Host colon 8,000 sorry not 8,000 sorry sorry 27017 it's a server port number SL my database name which is what Au demo right now so so Au demo just a revision just a revision rishikesh just a revision I'll copy the schema I'm just doing the connection revision because I've already coded it so we can copy the schema or we can also create it it will just take 2 minutes so dot then if it is done quickly just a revision so here we going to we're going to do actually nothing we need nothing if it is done then simply console.log DB connection successful okay I know my spelling is incorrect but that's fine and if something happens catch the error and please print it console.log print the error that's it okay simple all set all good now then guys let's also create the schema for users user okay so quickly go ahead con user schema first I'm doing all the database things mongus do schema only three Fields name username password that's all so name I'm not going to do any kind of main validations so I'm going to go keep it very simple type string and require true that's all I hope you know right you can also put your custom message here we have learned that so it's okay then email same then password same correct guys everyone I hope I don't have to explain you how to give a proper message right you know how to do it we have learned it so many times I think two times in the last two sessions so we can leave it on to this only three Fields basic validation done and then timestamps so timestamps true so that we can have the fields like I created at and updated at so time stamps true done all set all good and now then let's go for the model so this is schema for user and then scheme sorry we're going to be having model for user so const user model equals do model pass the collection that you want which is users as you can see here users is the collection name so users and schema which I want to follow is user schema which we just created simple done guys model schema database connection done now it's time to use express to create the end points so to start with that let me mention here end points the first thing that we need to do is create a Express object so that we can create the server and start creating the endpoints so first create a Express object and normally we call it as what app but again guys you can call it whatever you want but mostly app Express done with this and then create a server and start it so for that the function is listen which creates the server on the specified port number and also starts it and if the server starts correctly this call back function is called to make sure it is on just put a message in this call back function server is up and running guys done with the basic setup right see how easy it was properly mentioned the two packages then database connection schema creation model creation and then simply Express object and starting the server let's run this much to confirm if it is everything is working till now so node Monon index.js and yep see Server is up and running and database connection also also successful so all good now it's time to create the end point so let's say guys we are doing something like this let's say we also going to have something like this registration login create post delete post now this can be create product delete product right this can be create user delete user this can be anything this can be a dummy endpoint I don't care it can be any endpoint but my main aim is to secure these two endpoints these endpoints should be allowed only if the user is verified for that they have to login but before login they have to register so let's create an endpoint which will help in registration so guys let's go it's for creation of a new user so it should be a post request so app. poost okay and it should be let's call it a slash register okay request response okay simply enough now let's handle it so now guys how do we access post data how do we Access Data coming in request body tell me everyone how do we access that come on yesterday we learned it how do we access the data coming in request body let's see if you can answer come on guys everyone let's see if you can answer come on quickly chunk are you sure chunk yesterday we learned something else we can do it chunk by by chunk but only if it is normal request now we using Express right so we can directly access data in our request do body property the whole data is already there converted but if we want that the first thing we should do is we have to apply a middleware right and the middleware function name is express. Json this middleware job is to extract data from request chunk by chunk convert it to JS object and again give back to the request so in my actual endpoint I'll be receiving the data directly I don't have to do all that process because that process is done by this middle bear function right guys everyone I hope you remember please confirm that once so console.log just to check request. body see if we don't apply this middleware as we learned yesterday if we don't apply this middleware we won't be able to access request. body directly no we won't be able to access it remember that guys please okay then we have to do chunk by chunk logic we have to extract it by ourself from the request stream but if we do this this middleware do that job for us it will also do the conversion so we can directly access it see you guys are forgetting it that means you guys didn't practice anything from yesterday's session right guys didn't practice no issues I know you'll practice and send a dummy response so that the server doesn't go on hold so send let's say something like post working for now okay let's test the endpoint guys let's test this endpoint and guys for today I am not going to use Thunder client okay what I'm going to be using is something called as a postman which is also a testing client nothing else guys but it is one of the most famous testing clients and I think someone from you guys was requesting for Postman so let's use Postman today guys everyone because now I think from last three sessions we are continuously using Thunder CL so you know how to use it now right body is a packaged by Express place of writing code to get body is a property not a package body is simply a property which is created by this middleware this middleware accesses your data extracts it chunk by chunk converts into JS object and gives a new body property to your request object it's a middleware right that means it sends it takes the request performs some changes and again gives it back to the end point where I can access the request you know right middleware functions and your actual endpoints they get access to the exact same request object right UL okay so this is the middleware not a body how can a body be a package it's simply a property guys please don't forget the basic JavaScript request if request is OB object anything in JavaScript if you're accessing by dot it's a property so request do body body is a property but that body property is given by this function that function middleware function before the request comes to this endpoint it goes to this function I think yesterday guys we learned it in deep right hopefully yesterday we learned it I hope no one is confused everyone hopefully so if anyone is confused I would suggest you guys to watch yesterday's session again because yesterday we understood what exactly is a middleware and how it works and I also showed you how Express dojon function might be working internally I showed you that by writing code as well right how it might be working internally so before the request comes to your main end point it goes to your middleware function it takes it extracts data from that request and then gives it to this end point in the form of this property right let's test it now for everyone who are confused little bit and if you're new please you have to watch my yesterday's session as well okay now guys time to test it so let's use Postman everyone let's use Postman so to get Postman you can simply go online and search for Postman download and guys that's also simply a testing client that's all so you can simply go on this website first one Postman download and you can download it for free for Windows okay download it and install it like a normal software that's all download and install it like like a normal software and that should be it once you install it simply search for Postman in your PC open it and here we go it's open now and see you'll see it is exactly like thunder client only do you want to allow public and private Network yeah fine okay I'll allow Postman and see guys it looks exactly like your thunder client don't worry if it is too much because Postman is big software it does a lot of thing but we are not interested in that what we are interested in this just go here okay and click on this plus and that's it you'll get this option see that everyone see that same logic same thing get post put p delete URL click on send you can see your params headers here body here see guys exactly same right a response window a request window sending data as raw Json how do you want to send it exactly same just showing you you can guys you are free to use Thunder client till now you can use it completely I also don't use Postman a lot now but just wanted to show you that something like this is there which a lot of companies use okay so let's send a request from here then okay so it's going to be a post request my address is HTTP col SL Local Host colon 8,000 slash what's the route name register so let's go register that's all and see guys no params no query parameters no authorization nothing like that see headers in Postman also in Thunder CLI in Thunder clant also guys there are some hidden headers as I told you it sends it but it doesn't show you in Postman you can see it if you click on this you can see all the hidden headers that Postman is sending and that's fine you don't have to remove any of this leave that these are internal headers which the postman is sending for some dealing with the server you don't have to worry about it if you want to send any of your own header you can send here is that clear ThunderClan also sends as I told you earlier also Thunder clant also sends some internal headers but you don't have to worry about it leave that now in body which kind of data you want to send form data URL encoded binary we want to send raw data raw Json see in Thunder client you directly get option like this if you click on new request see so here you can select post you pass URL right and same logic see some internal headers even if you remove them it still goes internally even if you remove it is it still goes so doesn't matter and here in body we write our data okay and here we directly have option of Json here we have to go to raw and select Json from here that's the only difference and now you can type your data here so let's let's type a data name I don't know how much I can zoom it now I hope it's visible guys name let's say sorab then email let's say as Gupta and guys why can't I see the charts okay now I can see it es Gupta adate gmail.com something like that and password let's say s Gupta easy one is that clear guys everyone understood same thing we do in Thunder CL as well correct everyone can you please confirm once and now simply send so just like thunder cland guys nothing different in Thunder cland also we'll do the exact same thing we'll just go there you know post write the proper URL put this data here same thing exactly same okay but here in body we directly have the option of Jason here in body you have to select raw and then Json and now let's send and here we go guys post working now we don't have we have not inserted it in database difference between both see both of them are exact same thing it's like you're asking difference between uh life boy and DET all both are soaps exact same use right but from different companies from different providers same thing Postman Thunder client are exactly the same thing they are testing clients it's just Thunder client is more handy because it's inbuilt in vs code Postman is a separate software but yeah because it's a separate software it has some extra features as well like collaboration you can do team collaboration and all that stuff it's a high level tool so basis is same it's a testing tool but you can do team collaborations people multiple people can work at the same uh directory and all that stuff and you all can see so if I'm doing something I can share this thing to you and you can also see the exact same thing so a tool where multiple people can work together remotely that's what Postman is exactly like react and angular same things okay so guys just wanted to show you that it is like this okay so now let's go and see guys the data is coming here you can see in console the data is here so everything is working okay everything is working can we send mail address in header yes why not you can but why do you have to send mail letters in header it's possible you can send some extra data in headers but I think you should not send mail addes in header it depends what kind of thing you want to do Tes possibility is there but there should be a reasoning why are you sending mail letters in header because header should not be used to send content right for Content you should either use URL or you should send it through the body okay Tes okay no issues guys now then let's move ahead and now guys what do you want to to do we want to insert this data into database I hope we know how to do it we have the model we have to use that model so let's go user model dot the function is create in create just pass the data request dot body and if you want to keep it clean you can first store it in a variable like let user equals request. body Okay so now your object which was coming in body stored in this variable user and you can pass that user here that's it and then simply go ahead it also returns a promise so dot then you know you will get your user back so let's call it as doc but I don't want to send user back I simply want to send a simple response like response. send a message why am I converting it to Jason it's fine I can send it directly now message user registration successful and if some problem has happened then do catch see what's the error print the error for the user so console. log the error for the user no requirement yeah we should validate but right now thees we are doing only from testing client right we are only doing it from testing client that's why we are see we have a validation we have a database validation so as I said you can perform multiple kind of validation so the main validation will be done on front end and here we also have a database validation we are not doing any validation in the API as of now as of now we are not doing it but in the project that we'll be doing in that we'll be doing it we have have just started it that's why we are only doing database validation as of now and we'll be also doing front end validation when we create the front end application but right now we are not doing the API validation the coding validation right we can have multiple levels we are working with only one level right now because we are just creating this API for testing not for the actual use that is the reason but yeah we'll be doing that coding validation as well but technically normally you will not need it because you're doing database validation as well as the front end validation right so normally you need it uh what if I use insert one no you can't use insert one I don't think so you have insert function for model you have create and save only two functions because this is not your mongod collection DX so some methods are different you cannot use insert one I think you don't have anything like insert one in gives you create functions and save function only two ways of creation not insert one hopefully I've never checked it but last time I saw it was not there is it clear Drex buddy I hope you got the idea so you have create and save okay I have to check if they have updated something and they have got insert one so log the error and send a dummy response I have to check if has insert one because I'm not sure about that I have to check it's available directly in mongodb in terminal directly in mongodb query language not in some things in are different okay so let's just simply print some problem that's all so guys done with it first endpoint created right everyone all said guys cleared any confusion first endpoint is created Let's test it so now again let's send this request so 1 2 3 send and here we go guys user registration successful and now if you check your database base you have the first user name email password cleared guys but right now we have one issue we have one issue very big issue and the issue is guys if the owner of the database or owner of the company sees our database he can easily see my password and what if the person wants to use your password getting the point everyone this is very bad like now he or she can also log in and do something with your account so guys password should never be inserted in database like this any other data is fine but password should never be inserted in database in a plain text format because what if the database owner or the developer not even the owner let's say I'm the developer working on an application for someone so company and I open their client base and I can see all the user password I can log into do anything then right B can you explain difference between schema and model schema is a structure see let me just give you idea the just see schema is simply the structure which validates how the data looks like so it's a structure which tells how the data should look like that's all okay that means the data that you're going to be inserting for user collection it should have name it should have email it should have password simple and there should be type string that's all model is a object which connects your collection which is inside the database and the schema so it's a object which gives you a reference of that collection it's a object which actually gives you all the functions which you can use to work on the collection that you have in your database so in database you have a collection called users but you cannot directly access this collection from your from your nodejs so this model object is a a connection between your collection and your program which lets you collect connect to the collection so now you can use this object to do stuff you can use the model object to create update delete and whatever you do with this object is directly happening on the collection it's a reference of a collection you can think of it like that it's a just a reference of the collection because you cannot use the collection directly and second parameter while creating the model so first parameter is you tell the model that model you are going be connected to this collection and while doing things you have to follow this schema so while entering data in the collection updating data in the collection you have to follow this schema it should have name mail password that's what it is simple no no no yeah you can say that yes yes yes but model is simply a object which is referenced from The Collection you should not say model is the collection of documents collection is the collection of documents model is simply a representation of a collection ction it is not actually having the documents it simply helps you to access the collection is that clear it's like a mediator between your collection and your program got it a representative of your collection on the program world is that cleared Tes so guys as I was saying in your database it is not good to store your passwords in a plain text format as I said anyone Minds can be corrupt and they can use your password and that's why you should never store your password like this but you have to store your password but not like this so now what we have to do is we have to do something called as encryption of the password where the user will put their password in simple format but in the coding we will encrypt it in a way that no one can read it so we'll perform encryption of the password it will be converted to a cipher text Cipher means encrypted text that not even me or a developer or the encryptor can also understand no one can understand it so we have to encrypt our password is that clear guys understood the idea so not the owner not the developer not me no one can decrypt it no one can understand what's going on only the person who wrote it they will if they remember it it's okay if they don't remember it then they have to change the password even they cannot decrypt it no one has the right to decrypt it only if again it's up to me I can create such an application where it is possible but no we don't do that as developers we follow sincere rules and regulations if I do the other stuff where in front I show your password is safe and in the back end I'm decrypting it then I'm doing some kind of hacking or fishing and that's wrong that's illegal okay is that clear everyone got the idea so let's go ahead and let's see how to encrypt it now guys for encryption we again need a library we again need a module in node JS okay first of all guys are you clear with what is encryption we'll convert our normal password into a encrypted text that no one can read a cipher text that's what you call as encrypted text okay and for that there's a library called as bcrypt JS which we have to import see it's available on npmjs site this is what we need bcrypt JS okay it's a JavaScript based Library okay so we have to use this one so first of all let's quickly install it so all the things you can find here Cipher CI pH CI I think yeah it's CI pH okay so guys we have to go here stop the server for a second and let's install it so npm install bcrypt JS and guys bcrypt JS is not the only Library there are many more libraries okay but I'm using this one because I use it a lot and it's easier to as well so done it will just install it and all said guys now you have bcrypt Js in your project okay now you can also find how to use it here it's that simple you can also easily find how to use it here is that clear guys it's very easy just curious how will we how will we what how will we do manually what decryption first of all see decryption is not possible decryption is not possible is that cleared okay so see what we are going to be doing is we are going to be hashing the password not only encrypting we are going to be hashing the password see you have to search difference between hash hashing and encryption so you understand this encryption is the process of scrambling plain text into unreadable Cipher text which you can decrypt if you know the rules if you know what's going on in interally hashing turn plain text into a unique code which cannot be reverted so we will be actually not encrypting see it is generally called as encryption but what we'll be doing is hashing you should always hash passwords not encrypt see generally the term is encryption guys so we call it encryption but technically we always hash it hashing can never be reversed that means you cannot reclaim your password that's why guys on all the sides they if you forget it change it you cannot reclaim the password is that clear guys so encryption can be decrypted not hashing hashing can never be decrypted hashing algorithms are like that on again if someone tries I think it's it will take years for decryption by that time either the account will be dead or the user will change the password that's why all the sites suggest you after every one year two year please change your password please change your password but technically it's not possible it's almost impossible to decrypt a hash because they don't create in hashing they don't create those algorithms for decryption they only create encryption algorithms hashing algorithms is that cleared guys but I'm not saying it's impossible I don't know in this world full of certainties anything is possible but again it will take a lot of time so don't worry like anything is possible guys but we still have to do what we do right cleared so what we going to be doing is hashing not encrypting the general term is encryption but we'll be doing hashing so now see guys here you can see everything okay I'm going to show you the important points first import it okay so let's go and import we have installed it so require the name of the package is bpjs so bcrypt JS I'm showing you how to read the documentation and do it okay so bcrypt JS because I also don't remember exactly how it works so I always figured out how to do it from the internet I almost remember everything that I'm coding almost but sometimes you know I don't use the libraries from a lot of time so it happens so it's okay sometimes you have to refer some code and it's okay while doing it live it it is needed okay so now then guys first of all let's go in our database and let's delete the old data delete it because it's not safe and now come back to this now we have required it now see online and guys I'm okay I'm going to use Postman only okay where's my uh uh yeah now see there are two ways there is the synchronous way and there is also asynchronous way of doing encryption or hashing I am not going to be using the as synchronous way why because if it takes time it will block my code I don't want to do that so that's why leave that again guys it's fine you can do synchronous but I don't follow the synchronous a lot so I'm going to do it in the asynchronous way okay that we always use everything that we are doing so far is asynchronous so we will follow the synchronous way so now if you read it guys see there are two functions first you have to call the function called as gen salt which means generate salt salt is like a key which you mix while hashing so Guys Salt is simply like a key which you mix while hashing that's why it's called as a salt because you're using it in a mixture getting the point so it's a random text which will be generated internally and used internally is that clear guys everyone that's all okay so what we have to do is we have to generate a salt and see this 10 here means how many number of rounds you want the algorithm to work to generate a really unique salt so 10 Rounds five rounds up to you this is the number of rounds the algorithm will work to generate the salt is it cleared everyone so first let's call this function let's do it in our own way so no issues so guys please Focus everyone so bcrypt Js yes also guys why to give it so big name it's a complicated name let's simply call it as you know something like BC y something like B cry that's it or just bcrypt as they have named it online sounds much more better okay so bcrypt dot function is generate salt in which first you have to pass the number of rounds see it is mentioned it's rounds so let's say I'm also saying 10 Rounds okay it's safe 10 Rounds then it has a call back function in which you get two things if there was some problem you'll get an error otherwise you will get your salt which is nothing but a unique text that's all guys so now here I'm going to say if there is no error if not error that means if there is no error then what now guys my password is available in this object right everyone we know our password is available in this object this user object is having three properties name username password my password in the form of plain text it's available in this correct in the user object I want to get that password and encrypt it so now after that what is the next step so inside after generating the salt you'll use one more function called as hash in which you have to pass a dummy text or a secret key or something like that and then your salt that you have generated so let's go and not dummy text guys it's actually a password that you want to encrypt or sorry hash so see the parameters are hash the password that you want to Hash the salt and then it's a call back function which gives you return the hash password okay so guys let's do one thing for some time let's comment this whole thing that is happening so that we can see what's going on so response. send a dummy response so that the server doesn't hang so just something like working and let me show you now so if it is all set sortage generated then bcrypt dot hash now first parameter is the string password the password that you have my password is available in this user so user do password cleared guys I'm passing that okay comma the salt which is available from here so pass that here salt comma here you'll have a function in which either you get error if something happened or you'll get the N pass which is I'm calling as new password you can call also call it as hash so let's call it Edge password hashed password and then if again no error not error then simply let's print the hash so console.log H pass just to show you so guys got the idea on what's going on here everyone everyone can you read this codee and understand what's going on now we are at a big level guys so we have to do things like this okay so simple idea using the B Library generate salt pass it through 10 Rounds then give a salt to me if there was no error while generating the salt then hash what I want to Hash my password so which is available in user so user. password take this hash it with this salt and give me the new pass and if there is no error I'm just simply printing it let's test it now so now guys you see here I'm passing password as s Gupta let's see what happens with it send could not oh my server is off sorry let's run the server quickly guys time to test it send you got the response working that's not the case what we want to see the console and see guys what happened with your password see that everyone understood everyone can you see that what happened here so now this is your password this is the hashed password and this is what we will store in our database got it I hope you got the whole idea everyone okay and to read more about what is happening here you can always come to this particular Library okay and here see hashes are of 60 characters so you have got a 60 character password and that's even unreadable so it doesn't matter okay so you got a 60 character password why I'm showing you this because in mongodb it's fine but if you're using some other database like MySQL or something like that there you also have to mention the length right field length so there you have to mention it for holding 60 characters okay all cool then guys now see please understand done everything is done now we are again doing JavaScript so guys can't I just do this now I know that we have this object user which was having three properties I passed one of its properties for encryption hashing now I'm I know that in this I have the new password encrypted password hashed password so now what I'm going to do is I'm going to again access the property that users's property password property and I'm going to change it with the this new password this is plain JavaScript guys I hope you know I can change any objects property like this right everyone hopefully you know this we can change any object property like this okay and again if you're confused first of all watch my Js sessions second of all I'll show you something wait say guys if I have a object like a equals name equals sorab and City equals again guys it's some js concept so if I have something like this name s City Mumbai so now a is a object which is having name s of City Mumbai if I want to change that object City I'll just do a do City equals Pune just access the property and pass the new city and now if you check a see the city has been changed to Pune that means if you ever want to change a property of object you just have to access that property and change it with a new one so initially it was having Mumbai I printed it you can see it's Mumbai then I said a do City should become Pune and if I print a now City becomes punee same thing initially in my user it was having the password which was coming in the request that was s Gupta then after performing encryption I said now the user. password so just like a. City user was having a password property fine user password should be this new password so the old password which was having in here which was as Gupta will now be changed to then it's new password H pass and now after see and you know right you saw it here when you change the objects property the whole object is new now we have a name and we have a city which is new the whole object is new and that's what we want to insert now so now we'll take this whole thing and we'll put it here so once the encrypted password is generated then perform the insertion logic and that's it guys that's all see now now your registration will look quite big but don't worry it's simple to understand so if a request comes on register let me explain it to you if a request comes on/ register all good no issues take the body data then generate a salt okay hash the password which is in the user object okay then you'll receive a new password which is encrypted hashed and then change the user's password property with this new password and then insert it into the database and that's all is that cleared guys everyone are we cleared with this or not first end point done hopefully let's test it now let's go to postman okay you can see it's s Gupta here send and here we go guys user registration successful let's check our database and here we go see that guys our password is now encrypted see everyone all good got it guys that's how you do it okay now you even if someone directly hacks the database they still can't understand what's the password not the developer not even the owner not even a hacker no one will know what is the password now understood that's how things work so you have done your first step in authentication which is encrypting the password password while registration and now we are good to go for the login done with registration now add as many properties as you want doesn't matter now guys let's do few more registrations let's insert few more users so I'm going to insert Nanda as well so Nanda nand gmail.com and let's say password will be Nanda as well guys why I'm putting simple password so that we can remember it because if we forget then we don't have any way of remembering it okay so two users that's cool okay you'll have two users you can see both the passwords are encrypted and they are unique guys don't think that they are same both of them are unique okay so two users with two different passwords unique passwords Lov this part today of authentication thank you so much imas thank you so much buddy and guys also if you're new please don't forget to subscribe guys help me reach 2.5k at least by December let's see if we can reach show me your power and if you're enjoying it then only up to you again but let's go anyway let's go our a is to learn so let's go okay guys so done with registration now then let's move ahead to login so endpoint for login now guys in login remember in login what do we have to do user will send so I want my email to be username or email so I want the user to log in through uh you know email and password so I'm expecting email and password okay so let's go and guys login will also be a post request because the person is going to send email and password through body please guys login can also be a get request but if it's a get request that means you'll be sending email and password through URL you tell me is it safe to send email and password through URL no right because people can't see the password you don't want to show everyone the password in the URL that's why guys login should always be a post request because you are going to send some data and you want to send that data through request body so that's why it should be a post request we can make it work with get but in that case it will be visible in the URL so don't do that so app. poost so even though you are not performing any creation so login is I think the one and only end point where even though you are not performing any creation it is still a post Endo logins are always mostly post endpoint even though you're not performing any creation it's a exception think of it like that so app. poost let's call it login request response okay so guys what do we do in login very simple we simply check we simply check that the user and password which is coming from the user from the front end is matching with the username password in my database or not that's it we simply compare the username and password coming from the user with the username and password stored in the database is that clear guys that is what we do that is what we do simple we simply compare the username password coming from user with the username password which is stored in database if they match all good if they don't match wrong that's the logic okay everyone remember that please so first of all let's check this Endo if it is working or not so again people are going to send data through request body so let's print that request. body now guys again here have to focus okay you have to focus completely here please please please I want you guys to focus okay um and then just a dummy response so response. send dummy or just you know something like login working that's it okay let's test this endpoint quickly so again in Postman create one more endpoint it will also be a post request HTTP colon Local Host but this time it will be login and now guys we'll again go in body raw Json and we'll pass only email and password so email we know we have a s gupta8 atate sorry s gup gmail.com and password will be only s Gupta first of all let's see if this is going there email and password you got the response login working that means something is happening okay that means something is happening so let's go and check if we have it in the console or not because we have logged it right we have loged the request body data that means if this body data is coming in the API it should be logged and here we go see that it's here so guys endpoint is working data is available now remember guys you want to compare if there is one person in our database with this email and this password so it's a simple operation you can do user model. find one where email matches this and password matches this if we find a user that means there is a user so you are valid if you don't find any user with this email password that means you're invalid user that's the logic right everyone that is the logic that means if you find a single user who is having this email and this password valid user and if you don't find a user with this email and this password combination it's the invalid user but the issue is the user is sending the password in normal format and in your database the password is stored in encrypted format so how are you going to compare now that's the main issue how are you going to compare secondly it's a hash it cannot be decrypted so now how are you going to compare don't worry just like bcrypt gives you option of hashing it also gives you option of comparing so for that guys again if you go to this online web page and you'll see here for comparison also you have this yep you have this bcrypt do compare in which you simply have to pass your plane password which we are getting your hashed password which will come from database and that's it it will only give you error result that means you are not doing anything no decryption nothing simply your password and an encrypted password and everything is happening internally and guys internally also no decryption is happening no it is compared based on algorithm there is no decryption that means no one can see the password is that clear okay so no decryption you know what happens internally this is also hashed and both the hashed hashes are compared no decryption happens that means no one can see the password okay and if there's some issue in the comparison some error if no issue then the result and result will be true exactly so guys you again have to use a compare function in which you'll pass the current password that you're getting in login and the hash password which is stored in database so let me show you the process of how to do it ready guys everyone understood the idea so the first thing that we will do is based on the email will fetch a user based on the email which will fetch a user so first of all guys let's do this let user user cred let's call it as user cred that means user credentials okay because we know that in this request we are only getting email and password so let's store it in a variable called as user cred in which we have email and password nice now first of all the base process is based on the email fetch the user guys we can do it right exactly rishikes exactly so we don't decrypt and compare we hash this one also and then compare we never decrypt we never ever decrypt and both the hashes will be different again but the comparison will be done based on some algorithm that means no one can read the password okay so now guys first of all base idea get the user based on the email so for that guys how do we do it user model Dot now guys we know that for a single email there will be a single user we know that so find one don't do find find one find one where the email of the user matches the email which I have in this user cred which is coming from the testing client or from the front end is that clear guys so find one user where the email of the user matches the email which is coming in the request so if we find it so first of all if the find was successful then you'll get the user here and if something happened in the find then there will be some error and for that we'll just print the error so console.log the error and send a Remy response response. send message some problem okay that's it remove this one now and guys see also remember sometimes for a given email the user will not be there but don't think that's an error that's not an error because your query is successful see guys this error only comes if there was some issue while finding there was some issue if you have given a wrong email and there is not a single record with that email that's not a issue your query is still working fine so you'll get a blank object in that case remember that guys you'll get a blank object let me show you so let me print so guys whenever find one is performed you're passing the comparison idea if a user is found that user will come in this variable if nothing is found this variable will be empty okay if nothing is found that's not an error because query is still correct there was no data but query is correct right only if something happens some issue happens some internal error happens then only catch works so don't think that catch will also work if no user was found no finding no users is still correct because query is fine this catch is only for if this query goes wrong okay so let me print the user and also a dummy response something like post working okay just to test guys login working okay now let's see what is coming in this user for a given email okay so guys let's test it let's go in Postman now we know that for this email we have a user correct so let's send it okay see login working and if you see the console you got the user see that everyone you got the whole user back right when you perform find one you get the whole user back and you got it see that guys ID name email password everything you got it back which is stored in this user and let me show you if you pass a wrong email if you pass a wrong email some mistakes in this let's say now see what happens see still login working but now in your console you'll see what we got back was a null that means nothing was found for that that means this variable is null understood why I was said that this scatch is not for if the user was not found error will happen no it's okay if user is not found query is still correct this scatch is only if the query goes wrong so if you don't find anything the object is null that means what we have to do is now we have to do this if user is not equal to null then user was found so we'll send a response saying user found else a response saying user with this email doesn't exist or wrong username that's also fine let's do that why are we putting this much big thing wrong email understood guys everyone got the idea so now let me show you see so if I send this see that wrong email and if I send a correct email now user found we are yet to compare the password but at least user is found now if the user is found that means we are doing this first check if there is any user with this email yes okay now then check the password now check the password so now if the user is found that means if user is not equal to null if it is found now we'll check the password and now we know guys the password which is sent by the front end it's available in this user cred and based on the email we also fetch the user so the encrypted password so guys the hashed password is available in this object as we saw by printing right see the hashed password is available in the fetched object from database and our password is available in this so now we have to compare so if the user is found bcrypt do compare first your password so user cred dot password which we are receiving from request from front end or from testing client comma my has password which is available in this user user. password okay see guys the field name is password okay so this user. password please compare both of them and then either error or result so if result is true we are sure that the S connection like it is Success so if result is equal to equal to true then we'll simply say login successful now it's correct response. send message login success else message incorrect password that's it now check it out let's go here we go send and see guys oh there's some issue what happened crashed what happened what happened what happened oh guys see I our variable name is also RS response variable name is also RS and here also I'm calling it RS so better it's let's call it result got the idea my program got confused so let's call it a result I named two variables exactly same save it okay now it should be done so now if I send it see guys login success now wrong email so we get wrong email okay correct email but wrong password any password incorrect password and if it is correct password then login success so guys your complete registration and login system is built now it's done got it guys so now you're able to register with proper encrypted passwords hashed passwords and now you're also able to login and now it's up to us what we want to do after login don't worry I'm also going to teach you that but guys first step towards authentication is done so guys are we cleared with this everyone are we cleared with everything till now guys can you please confirm that and I think you guys are enjoying right are you guys enjoying or not let me just have some water till then and you tell me are you guys enjoying or not if you are please guys if you're new subscribe to the channel and also like the video as well show me how much you're enjoying and understanding everything show me by doing the likes okay cool now then let's move ahead towards the important things again everything was important till now but now guys let's go back to normal so let's go back to our browser because now we need to understand something very very very important now now see guys so far we have already learned that our front end will be on different server correct our back end will be a different server correct guys we have learned it our front end our back end and our database they are three different places they have three different Origins that means you can treat them like three different applications R API is a separate application in itself our front end will be a separate application in itself okay try to understand guys okay so our API is a completely different application and our front end will be also a completely different application that means they are not combined together it's simply like this is one front end application so if I have to explain you this see this is our front end and this is our backend server so this what how they are working frontend is sending a request API sending a response they are not connected simply it's like this it sends a request closes the connection it sends a response closes the connection see guys they are working on HTTP protocol and HTTP is a stateless protocol that means it goes does the job and ends HTTP is a stateless protocol okay that means it doesn't have any state it goes does the job and closes that means the front end sends a request and closed the stream is closed forever the server sends a response and the stream is closed forever and from a single API multiple frontend sources can also communicate this can also do the exact same thing this can also do the exact same thing and this can also do the exact same thing getting the point guys getting the point everyone previously this was not the case if you go back 10 years this was not the case at that time guys front end and backend were created together there was only one single server where front end and back end were working always together in a single server but there were issues at that time that means you cannot have a separate back end you can have a separate front end even though they are called as front end back end they were created basically you have to integrate them to work with them so they were working collectively not separately and the problem was then the same back end cannot be used with any other front end because it's already integrated with one front end and the same front end cannot call any other thing because it's already integrated with one back end okay so at that time backend front end were together so whatever back end has whatever data back end has front end can easily access it and whatever data front end has back end can easily access it getting my point everyone so what I'm trying to say is previously the idea was there is only one a server in which my front end files my backend files are together so it's a single computer in which my front end back end files are together so if anything is created by front end backend files can also access it if anything is created by backend front end files can also access it that was the case this was called as monolithic architecture of creating applications this was called as what guys monolithic architecture of creating applications but now what we use where we have front end separately and back end separately this is called as the microservices architecture is that clear guys this is what we call as a microservices architecture getting the point everyone front end separate back end separate as two different applications okay service architecture micro Services architecture whatever you'd like to call it the benefit of this is you can have two separate applications which are talking to each other and the same back end can be used with multiple front ends and same front end can also called multiple back ends and because of this only guys today's world is possible that is how Instagram can load Facebook things Facebook can load Instagram things you can open a Facebook article in your web page you can open a YouTube video in your web page that is the reason that is the reason these stock market applications are working that is the reason apps like zero and everything can access data from uh Bombay Stock Exchange and all that stuff so if I'm a company I'll create a API for my data let's say I'm a company okay and I have some data for myself let's say my job is to I you know what I do I go ahead place by place and I do census I extract population data and people's name everything and I create my own API and I create endpoints now you as a front end developer can access my API and create a good-looking application that's how things work and multiple people can do it that is how today's world is possible that's how from Instagram you can go to Facebook from Facebook you can go to Google you can have a Google button on your page right because of this microservice architecture everything is possible in now today's world understood guys so Facebook's front end can talk to Google's backend Google's front end can talk to Instagram's back end and load whatever they want again only if you allow the access but that's how things work now why why I'm you know telling you the story because you know right there's always a reason when I tell you a story there's always a very important reason behind it so why I told you all this story here it's important important but why so now guys see Focus so now you logged in you send username password from here it was checked in database it was correct so you logged in now you're logged in but you know that connection is closed connection is closed right so now you after you send username password okay and you're logged in and the connection is closed and now if everything is done how will the server remember that this was the front-end application which actually is logged in because there can be 10,000 front ends which have logged in so how will server remember that this was the frontend application which was logged in and I have to allow this front end application to access my create post and delete post getting the point server has to remember you right you sent username password I checked okay you are there I sent you a success message oh you are there but now stream is closed connection done so now if you send a new request to me how will I know that you are the correct person getting the point everyone getting the idea or not think of it like this think of it like this uh you go to a doctor's place okay now there are a lot of people already sitting in line around 10 20 people and it will take around 3 hours so now you say you just identify yourself that my name is so and so and I'm going to come later on you tell the receptionist my name is so and so so you authenticate yourself my name is this I live here and I'm going to come later on okay now you say I'm going to come later on and now let's say you come on next day now you expect the receptionist to identify you how like why receptionist should believe you getting the point now they know you face see as humans we know the face that's why we will remember but if you what if you come after one year how will they remember you as humans we have tendency to remember face but what if you come after one year that is why they give you a token this is your number 24 with their medical sign and all that stuff okay take this and next time when you come back please take this with you and show it to me and I'll understand that you were there even though I don't know your face from where you come from you come come to me give your name I create a token for you give you number write your name write my name signature and take it go back and now come wherever you want come whenever you want just show me this token if you show me this token I will understand that you were the correct person so when you came first time you authenticated yourself you told me that who you are then I give you a token and next time when you want to use any of my service in this Clinic just show me this token if the token is correct I'll let you use I'll let you go to the doctor same thing here now when someone sends a login request good if the username password is correct I'll not only send a message that oh you're all good you're logged in no I'll also send a uniquely generated token so I have to now generate a unique token and I'll send it to that API server or frontend server now it's front end's job to keep that token with itself anywhere I don't care it's your job keep it with yourself and next time when you send any request for create post or delete post please send that token in the request and before letting you access my create post I'll check the token only so basically I'll be having something in between I know you understand what I'm going to have in between so before letting you access my main end points I'll be having some functions in between now guys whatever functions we have in between they are called as what middle wees yesterday I showed you one middleware which was converting data from request now today we'll be again using some more middlewares which will check if the token that the client is sending is correct or not only if it is correct then I'll let you go to the actual endpoint otherwise I'll block you then and there I'll block you then and there understood guys that is the importance of token and that is the importance of middleware so that you can stop the request check it do something and then let it go or simply send it back from there you got the idea guys everyone understood what we are doing so now we have to generate a token and send it back to the client and client will do something with that token he will keep it and then whenever he sends a request he will send it back and it's my job as API developer to make a functionality which will check if the token is correct or not understood guys everyone got the idea and the token now see guys there are multiple ways of doing this token logic okay but what we're going to be using is something called as JWT token which is simply stands for Json web token a token which internally contains some Json data that's why the name is JWT token Json web token okay and again guys for that don't worry there is a module which will help us so if you simply search for Json web token JS you'll get this first one link and here everything is mentioned you can read it here but don't worry I'm going to teach you everything just showing you that everything is mentioned here I don't know why it's not loading what happened buddy why you not loading yeah now it's loaded okay so you can see all these things here okay so guys remember when the user is logging in and if he's successfully logining if he is successfully logged in then we'll sign a token signing means creating a token or issuing a token call it anything guys signing issuing creating so we're going to sign sign a token or create a token and send it back to the user that's the first task let's do it ready guys and also guys tell me does it sound exciting or not everyone is it sounding exciting or not tell me that as well come on you're learning something really great and new like one of my very important things I like this I like doing this authentication and token logic because mostly it is not available on internet while learning I faced a lot of difficulties when I was learning okay then let's go so first of all install the package install package name is Json web token please put the correct name Json web token without any spaces enter it will take half second and here we go done now guys our job is to First import it so again require and guys the name is Json web token but now guys see we got our first biggest name it's a very big name and it will be tough for us to use again and again so simply call it JWT okay guys please don't change this name this is the package name it should not change you can change the variable name so I'm calling it JWT simple now then let's go here so here I want to do it if the username password is correct here I want to perform so generate a token and send it back guys yesterday we learned right about middlewares hopefully you remember it middleware is simply a function middleware is simply a function which sits between the request and the actual endpoint there are inbuilt middlewares and you can also create your own middleware yesterday I showed you which has the access to the exact same request response which will be available at the actual endpoint it has the exact same request response you can read the request do something let it go you can also block it so for token checking we are also going to create our own middleware okay we are going to be creating our own middleware today yesterday also I showed you but today we'll be doing something else is that clear guys everyone okay so let's go so guys for generating token I'll show you how to read the documentation so see very simple this is the logic asynchronous way sign asynchronously there's a function called as sign in which you'll pass some data guys always try to pass data related to the user who is logging in so that in token also you'll have the idea of who is the user and you have to pass a private key a secret key which will be only secret to the developer or the company okay and optionally you can also mention the algorithm that you want to use for token generation even if you don't mention it by default the algorithm that is used is this one it is mentioned somewhere yep hs256 if you want to read more about it it's a encryption Alor them see okay so then uh full form you can also see the full form it's hmac with sha 256 that's why HS hmac is one algorithm sha is one algorithm so they are combination of two different algorithms okay so it's very big thing guys so this see you have to go very deep in this only only if you're planning to learn cryptography where you be learning how these algorithms works if you want to go in you know network security then only you have to go very deep in this as a developer just try to know about two three algorithms and that is enough is that clear guys everyone that should be enough okay so it's a combination of hmac and sha and 256 is the bytes okay so by default it does that but if you want to change it you can mention it here separately where is that so you can also use the RS but we'll use the same normal one but again just showing you that this option is there if you want to mention it okay so let's generate a token guys the function is JWT do sign first is something related to the user so guys you tell me can we directly use the username or the email because that is unique to the user right try to always pass something you need to the user so I'm going to use that I'm going to pass the user email so email user cred do email is that clear guys so I'm only passing the email don't pass the password no need okay if you B mistakely pass the unencrypted password then someone will decrypt the token and they can read it that's why don't pass password or something like that so I'm simply passing the email something unique to the user okay that's all so guys remember J WTS are generated with three things header okay head header payload that is data and the secret key JWT tokens are always generated using three things the header which is the information of the token the payload that is the data of the token and third thing is going to be uh the secret key headers are already defined so you don't need to mention it you're passing the payload that means some unique data for that user who is issuing this token for whom you're creating the token second pass the secret key and again guys it's up to you it's up to you okay your company so let's say I'm passing torab as my secret key torab key something like that normally don't hardcode it store it in a separate environment file or somewhere and pass it from there so that it's not directly readable by someone okay but for now it's okay for now it's okay is that clear guys and then finally you'll have a function here in which you'll get two things either error see I'm not mentioning the algorithm I want the by default hs256 so I either you'll get error or the token okay so error or token so now if not error then let's send the token as a response so response. send the token so guys I'm calling my property has token also and my value is this again guys this is just a property you can call it ABC whatever you want but again guys you know right it doesn't make sense that's why token this is my property name and this is the actual token and guys if some issue happens like again see everywhere guys everywhere I have not done the error handling I have not said if error happened see if no error then this what if there is some error so guys for that also you can just apply else and send some problem response getting my point I'm not doing it everywhere just telling you so if no error then perform this if error then in else you can pass a Dy response some issue happened server issue happened just to give a error message but I'm sure that nothing will happen like that that's why I didn't do it but here let me do it if something happened in token generation just to give you idea that you can do this response. send I'll send a message some issue while creating the token that's all simple and then please try again after some time something like that leave that okay done guys done that's what creation is so if the user is there and if the password is also correct generate a token and if there's no error in generating send that token back if there's a issue then some issue while creating and now guys time to test it let's go let's perform login so now guys we know this is a correct username password send and guys okay I think my application is not running so sorry let's run our application quickly and here we go and see guys you got a token and guys JWT is see how to identify if something is a JWT very simple it will always be three three set of characters separated by dots see first dot 2 dot3 always so remember guys a JWT is created using headers and uh what do you say payload and what else was that I told you secret key in our JWT logic header is already there we're only passing two things payload which is data and secret key and your GWT will always look like this is that cleared everyone hope you got the idea and now see guys even if someone finds this token even if someone finds first of all no one should find make sure that you're a good front-end developer so that no one finds it but even if someone finds this token and if they decrypt it they can only see the username and that's fine they can only see the email that's fine email is public right everyone email is already public so it's okay so guys are you understanding everything till now or not we have got the token and now we need to do the final thing okay now we need to do the final final Final thing which is let's create a endpoint a very secret endpoint the Endo which I don't want anyone to access now see guys please don't make your login and registration endpoints private because they should be public anyone can login or sign up but now I'm creating a dummy endpoint guys I'm creating one dummy endpoint which I want that no one should be able to access without the token that means it should be only accessible if you have logged in so let's get an endpoint AB do let's say simple get request it's okay slash let's call it as get data okay and guys right now no important some dummy thing is fine because I'm just showing you how to secure the endpoint whatever you're doing inside the endpoint that's your job right that's up to us we can do whatever you want access database delete product delete the whole company's database it's up to you I'm not telling you to delete your company's database up to you do it at your own risk don't do it guys just kidding don't do it okay bad thing okay fine but again I'm just trying to say do whatever you want inside doesn't matter so response. send I am a bad developer with a good heart okay that means we can do bad things something like that okay good again I'm just putting a lot of lame jokes here but it's okay okay so now guys we have this end point right now this endpoint is public that means anyone can access it let me show you because see have we done any security no so if I go now and try to access this end point let me show you if I go and try to access this is endpoint a get request on get data you can see it's accessible see you got the data back right guys everyone that means right now this is the public end point correct everyone got the idea so now what I want to make sure is no if you're accessing this endpoint first you have to let me know that you have token or not so for that guys we are going to create a middleware which will block the request from coming directly here now I really hope guys yesterday we learned in depth on how to create your own middleware right same thing guys exactly same thing so we'll get a function let's call it as verify token again guys function name can be anything as I told you a middleware function also receives the exact same request object exact same response object and one extra function which is called as next so whatever request response object you're getting here you get the exact same object here that means whatever you can do inside here you can also do inside here but it's your job to understand what to do okay everyone and I'm going to call this function in here right that's how you call the middleware so I'm saying that before calling this end point I want this middleware to work I want this middleware to sit between the request which is coming on this URL which is trying to access this endpoint I want this middleware to sit between that and now what to do I'm going to decide is that clear everyone guys understood so I want the user if you want to access this endpoint please please please send a token in the request so how how a token is sent let me show you token is also sent via headers so this is the token that we generated guys so if someone wants to access the endpoint I'm expecting that you'll send me that token and guys token is sent via headers so you have to go in headers now in request headers go in request header don't worry about the head headers keep them it's okay generate your own header now and guys token is always sent in the header named as authorization okay so guys see what you're doing is you're letting the user know sorry you're letting the user use a endpoint based on if he is the correct person or not this concept is what we call as authorization letting someone use something based on their roles based on their who they are like for example uh something like you know let's say I go in a company now it's CEO's job to stop or start the service I'm not allowed so he is authorized to do that I am not it's the CEO's job to take any laptop and go home I cannot do that getting the point that is what you call as authorization someone having right to do something so I only want someone to access this endpoint who is having token that means I want only the authorized user and who is the authorized user anyone with the token is a authorized user got the idea guys this process is what you call as authorization only letting the people access the endpoint who have the token who are authorized to access that's why the concept is called as authentication and authorization so there's a difference authentication means checking for a valid user authorization means allowing a valid user to use some resources got the idea that's the difference between authentic sometimes people get confused that's why I just wanted to make it clear here okay so guys that's why the token is also sent in the header called as authorization so guys here to send the token use authorization and the value please don't forget pass a value called as beerer why because you're the token beerer you have the token so you this process is called as beerer token authentication authorization so you have to pass beerer space your token that's it guys that's what you do beer space token okay full token beer space token that's all so you're sending authorization so see guys already there are some headers going internally don't worry about them you're sending one more header authorization and in that this yes you should always include beer see you can also work without beer but that is not how JWT should work so you have to follow some rules see guys there are a lot of things here that I can personally change but again rules right everyone there are some conventions that that we follow so it's a rule to always pass this because every right now it's my API server so I have the ownership of doing anything but in reality if you're using some other API and if they are using the same logic then you'll fail that's why this is the universal convention that we follow this beerer means that I'm the token beerer I have the token that's why beerer okay so beerer one space only and then your token and again guys the API developer will always tell you the rules so it's okay okay so guys now you're sending a header in the request so guys as I've told you whatever is coming in the request whatever is coming in the request in which object is available either the URL data or the body data request body data or the header whatever is coming in the request I I think on the first day only I told you whatever is coming in the request is always available in the request object even my URL data which I read using request. par. URL data if I it is a body data then I use request. body even my headers are available in this so let me show you okay so console.log your request object has a property called as headers in which all the headers coming in the request you can read and let's send a dummy response coming from middleware now let me ask you a question guys now if someone calls this endpoint they will first go in middleware they will not go to the actual Endo we know that they will first go to the middleware correct now tell me from this middleware if I have this code from this middleware will they ever go to the end point or they will be back from here only let's see if you can answer according to what you have understood will they go to the actual endpoint or will they come back we know right right they will come back why why guys because we have not used the next function next function is what moves It Forward exactly and right now we we don't want to move it forward we want to do our job first okay we don't want to move it forward so leave that we don't want to move it forward right now so but at least we know so that's good we know we know that's good so first of all let's see so guys right now this token will work okay if someone try to access this Endo they will not go to the actual endpoint they will go to this function and from that function it is never letting it go to this main end point so we'll be coming back from here and that's fine for now it's fine let's check it out so send and see that you're getting coming from Middle where that means you're coming from the middle V you're not going to the actual Endo you're coming from the middle V that's okay what I want to show you is see this guys we have printed all the headers see that everyone so see accept header host header connection header see internally some headers are sent which even we don't use as I told you always some headers are sent internally between client and server and some are mentioned by us and what we are interested in right now is the authorization header so guys see I have done request. headers which is printing a object which is collection of all the headers so I want to access only this first header again guys you can access any header you want up to you depending on the need but I want to access this header so request. headers is a object collection of headers I want to access the authorization header so request. headers is a object dot I want to access its authorization property which is this one which will give me this value let's see if it is working send and now we should be only getting the data not the header see guys now you're only getting whatever is in the token you sent message string form for the first time this one right yeah that's fine because right now it's a dummy response we'll change it no issues yes that rishikesh it's just a dummy response that's why a simple string send is allowed to send everything in end we can only send strings in send JavaScript data array of objects simple string anything is allowed Express Express okay so now guys you got this now from this I want to extract my to so guys see this is just a big string that's all if you split it if you use the JavaScript split function and you split it based on Space you'll get an array on which beer will be on the zeroth index and token will be on the second index correct guys everyone so what we'll do is we'll split do split the string based on space and now you will see that you're getting an array of that's what split is Right everyone remember JavaScript split so I'm splitting the string this whole string based on space so I'm getting this as my first index and this is my second index which is 0o and one so zero on zero we have beer on one we have token and I only want to access one I'm using the shortcut guys this is basic JavaScript not even nodejs and now I should only get my token so send and guys now from the headers we have extracted only the token which we want to check and that's it you got the exact token so guys let's store it in a token variable so let token okay guys you got the token everyone coming from the header and now you want to verify the token if it is correct or not so let's go and let's do it so again guys let's go to the browser because I want to show you so this was for creating token jw. sign now if you go down here you'll also get how to verify it it's very simple guys I know the function but I want to show you see this is the one jw. verify pass the token pass the key that you passed while creating the token and that's it you'll get the either error or the decoded token if there is no error that means token is correct if there is error that means token is incorrect so error comes if the token is incorrect so let's use this so here I'm going to do this see here we created the token here and now here we're going to verify it so JWT do verify first pass the token that you receive from header second pass the exact same key that you passed while creating the token which was torab key so pass that here and then a function in which you'll get error or the decoded data so let's call it as data same thing and now guys if no error then I want to let you then I want to let you go to the next end point so guys how do we send it everyone tell me what do we use to send it to the actual endpoint where it was intending to go we simply call what next that means there is no error so token is good go ahead all good but if there is an error then from here only I'll send a response invalid token please login again is that is that cleared guys that's all done you're done and also if you want to print guys you can see before sending it you can also print the data coming back you can also see what's coming in the data and now let's check it guys let's see if it is working then so now we should receive the response which is coming from what okay first of all remove this so if the token is incorrect we'll receive invalid token if the token is correct then the data will be printed and we'll move on to the next end point which is this and then we should get this response let's see so token is correct send and here we go guys I'm a bad developer with a good heart got the actual response so middleware checked it it was correct it lets you go to the next end point Main end point and you got this response but if I make a mistake in token let's go I'll just remove a c from here or let me just remove this first E from here that's it only one e removed wrong token send and see invalid token please login again got it guys everyone that's how things work you have done it everyone you have done it and if you see the console guys in your data you get back what you inserted remember guys while generating the token you inserted some data email which was user email so while verifying the token you again get the same data back but with only one thing which was the issue time time stamp when the token was created you also get that okay that's it so guys now you know how to perform token authentication now you can see this is only one end point you can create 10 end points and pass the same middleware to all the 10 end points so now all the 10 end points will be protected and the PE the person will need token to access those end points and the person can get only token like person can get tokken only only if they first log in otherwise they can't is it clear guys everyone are we cleared with this can you please repeat creating token creating was done half an hour back utpal okay I'll repeat it don't worry I'll do that but I think you should watch the video again because it was done half an hour back so I think you missed half an hour see creation is very simple you just need a package called as Json web token okay JWT I've named it JWT and once the login is successful you just have to do jw. sign pass some data unique to that user I'm passing email so whatever user is signing up pass some data unique to that user some secret key which is up to you and then in that it will generate a token so if there is no error your token will be generated and if it is generated I'm sending it back to the user and to verify it I'm doing this verify pass the token which is you're receiving from the header and then pass the secret key which you exactly passed while creating a token and then if there is no error it's good you can use the data and I'm sending it Forward okay go to the end point otherwise invalid token so all cleared guys everyone please confirm that are we cleared now one more thing see for every response even if it is a wrong response ER response we are getting 200 okay and that's not good see bad response good response a response is a response so by default my server is sending every response as okay good okay because every response is a response so even if it is a problematic response it's okay so so I don't want that I want to send different status codes for different response so that so that it's easier for the client to understand now if you remember guys on second day only we discussed status codes are nothing but numbers which help the client to identify what kind of error is going on easily much more easily by just using the numbers right now every response is going with 200 because everything is a successful response but I want to change it so let's see let me show you how to to send your own status code because by default response. send sends 200 even if it is a wrong response invalid token so let's see how to change status code and for that first of all understand what should be the status code for a invalid token let me see and guys again don't remember it just search it res just search status code for invalid token it should be if you read it it should be 401 got it guys so now while sending this response before send add one more property called as status I don't know why the hint is not coming status so response. status. send and I'm going to mention 401 here save it now let me show you so if it is 200 no need to mention 200 by default it's 200 but if it is anything else please mention it so 401 now let's check it now if I send this see see that invalid token and your response code is now 401 unauthorized let me also show you guys Response Code for successful creation it is 2011 2011 that means see when I log when I register myself that is also giving me what guys 200 so again come here as well when the user registration is successful that means created simple so please send status 2011 and guys see this is only if the query fails correct this catch will only work if the query fails so if the query fails that is server issue that is server issue right so for that what we'll do is simply send status 500 which is internal server error because we don't want the user to know what's going on my query failed my database server got some issues so just 500 internal server error so if you ever feel that you just want to print some problem that means you don't want the user to tell exact problem 500 internal server error something happened at the server I don't know is that clear guys everyone so see now you can also check Response Code for successful login okay let's check it what is it 200 so yeah by default 200 so no issues it's 200 only so leave that so guys are we cleared that's how you have to research about what you're doing and what kind of status code should be there is that cleared everyone and just mention it like this do status. send so in the status you can mention the status so guys are we cleared with the whole process of registering hashing the password and then login generating the token okay and here also guys you can send status of 500 internal server error if the token generation failed that's it and yeah for incorrect password also you can can send like you know see if there is wrong email that means user was not found correct guys so for that you should send status of 404 wrong email no user found simple 404 right everyone so if there is wrong email while logging in 44 wrong email no user found and you can also check what is for incorrect password so let's say user was found but password was incorrect check it Response Code for incorrect password it's also 401 so it's okay you can also send 401 okay so guys see that's how you create a proper good-look API and guys see you know there is only one thing that will stop you in mastering all this and I think you know what is that right lack of practice I'm able to do it so fluently because I have done it around I don't know maybe 60 70 times in projects and while teaching that's why I'm able to do it so fluently even I have to refer some things so understand you have to at least practice it 10 say you know not 10 15 times but in every project but for now at least practice it once or twice and then after that in different you can apply it some websites send web pages or images when there is error how to do that no they don't send web pages now see I'm not saying that sending web pages not possible but they don't send web pages they send this error based on this error the front-end server generates that web page getting the point just like front end server when it gets data from API it generates a good-looking web page right where you can see the data products and all that stuff just like that when the AP AP server sends 404 front end server generates a web page 404 not found got the idea rishikesh so it it is different the idea is different so normally API doesn't send the not found page API simply sends the status not found now you front end server your job is to generate a page so guys I hope we are cleared with all the thing that we have done so far and guys please it's my kind request to you at at least practice what we have learned today and yesterday if you don't practice that then the project that we're going to be building tomorrow will be a little tough for you okay so please now take this time forget about the old things because those things helped us to learn this now your main focus is this okay so please just sit and practice registration encryption hashing login generating tokens and also creating some end points for for get data and get products and create product see all the end points we created today yesterday now guys you tell me all the endpoints we created Yesterday can't we secure them with this logic then can't we just perform registration and login and then secure all those endpoints with the same verify token middleware can't we do that you tell me can't we do that so we had five endpoints yesterday so we can create two more endpoints registration login and then generate token and the other five endpoints forg get products create products update product delete product we can secure them using the verify token so guys please I'm requesting you to practice please please please do that so that we can create tomorrow's nutrition API it's going to be very important it's going to be big so please be prepared for that as well guys tomorrow session might also go till 2 hours or 2.5 hours so please be ready it's a project session and guys please if possible invite your friends and colleagues as as well if possible do invite your flags and colleagues Hi wasu how are you buddy you joined at the end today so guys tomorrow's day is completely about project so please invite your friends and colleagues and guys it will be the culmination or combination of all the things that we have learned so far so guys so far and guys yes now if you even only know this much you are API developer I'm not talking about any other things any other things you have to definitely learn but if you just practice and master what we have learned in the last 7 days trust me you are API developer trust me because if you know how to handle request send responses divide your code properly you're API developer proper handling of headers verifying headers all that stuff you're API developer only thing is now you have to master it a little bit by practicing and learn more about how to optimize your code and divide your code but all those things are secondary first thing is gaining the skill polishing it making it look good is secondary okay some reasons can't see live but download and see okay that's amazing wasu thank you so much please do watch it before tomorrow's project so yep guys that's all for today thank you so much I hope see today's session was I know a little bit complicated not complicated but you know a little bit tougher than all the things that we have learned so far but again guys we are moving towards Advanced Tropic it will get a little tricky right we are at the advanced topics because if it was very easy then everyone will be do it but I'm not saying that everyone can't do it with enough understanding enough practice right guidance anyone in this world can become a developer trust me with enough guidance right practice enough enough practice right guidance anyone can become a developer some people will take one year some people might take 6 month some people might take two months but trust me initially it might be little easy and at some point of time it will become tricky like these things are tricky and these are the points where people leave things they understand Basics oh good everything is good but when they come to this point they think oh it's getting tough and then they leave it this is the point where you have to sit put your mind and practice okay and break things down properly Frankly Speaking I felt bored but also because of your because of you because of you learned all oh that's great why did you at Bard utal because there were so many things today yes yes Basu it's there it's there it's a essential session it's there why why did you get bored today what happened was the session not good I know it was long and sometimes things will get long and sometimes guys also remember sometimes things will you'll face things which will bore you a little bit like long topics like this and again again it's perspective it depends on people to people but again push yourself practice enough and it will be good okay because of the topics I don't like so you don't like these topics but again you have to practice it trust me once you practice and do it you'll like it because initially when I was also a student these things were not good for me I was also uh you know avoiding these things I used to create basic stuff and avoid these things because it was very tough for me to understand initially but once I practiced understood things in deep it became very important for me important part of my life doing all these things providing proper security to my apis that's great that's great buddy yep so yep guys that's all from today now then I'll be seeing you directly in the project tomorrow so be ready and please invite your friends and colleagues as well and guys if you're new please don't forget to subscribe to the channel okay and yes authentication is important it is a core part of any application so sometimes it sounds boring see things till the time they are easy it's okay but things when they get tougher we get the feeling oh it's tough It's so much cold it's long it's boring but that is the place where your patience gets tested so yeah good day no issues guys so see you tomorrow everyone please sit and practice this and what we learned yesterday at least please practice and guys WhatsApp Channel link is in the description please join the WhatsApp Channel link as well so that you can get the updates and please follow the Instagram as well and that's it guys I'll see you all tomorrow and I hope that you're enjoying the session so far if you are please like the video and that's it no no no wasu no no I'm still very uh small you can say that okay bye-bye everyone bye-bye wasu rishikes shashini bye-bye guys good night everyone bye-bye good night
Info
Channel: Thorabh Codes
Views: 2,076
Rating: undefined out of 5
Keywords:
Id: QQOp1Cs00WY
Channel Id: undefined
Length: 135min 50sec (8150 seconds)
Published: Fri Dec 01 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.