Protect Routes with Middleware in NodeJS - Rest API with NodeJS and MySQL (2020)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we can learn how to add the middleware to a node.js api the purpose of the middleware is to protect some routes and give access only to authenticated users so let's get started hi guys it's kaurasam here and this is the part nine of the series building a rest api with node.js and mysql so make sure to subscribe and stay with the channel so you can follow the rest of the series all right so so far we have done implementing crud and request validation authentication and so much more so today we're gonna add the middleware and protect some routes so that only the authenticated users can access those resources all right so first of all i'm gonna create a new directory uh i'm gonna name that middleware so that i can include all my middleware here inside that i'm gonna create a new file i'm gonna name my middleware file check auth so that name makes sense because we are checking if the user is authenticated and here i'm gonna define my middleware function here let's import json web token package just like this and i'm gonna create a new function i'm gonna name that function check auth here as the parameters just like we did in our controllers request and response and we have to pass additional parameter called next i will explain this parameter in a minute uh now here i'm gonna add a try catch block here because uh decoding a token can cause errors so in order to handle that errors so we can use this try catch block so that you can handle that terrace very easily just like this here inside this try block i'm gonna define a new constant i'm gonna name that constant token now we need to get the token sent by the user for that i'm gonna use request dot headers and earlier we use request body for saving a product and updating a product we use request body but normally we used request headers to send a token all right in the headers we need to get the authorization header just like this and authorization header string will be something like they are space then the token just like this so we need to extract only the token from this entire string for that i'm gonna use this method called split like this and we need to split that string uh by this space and we need to get the second half of the uh splitted string all right so this will be the token sent by the user now we need to decode this token um for that i'm gonna create another constant i'm gonna name that decoded token and for decoding the token json web token package has a function called verify and as the first argument of this function we need to pass the token oops and as the second argument we need to pass the secret we used when creating the token in our user controller right here we use that we use a secret for generating the token so we need to use the same secret here i'm not gonna just hard code it again instead i think now it's a good time to create an environment variable file um since we are using node mode we can do it easily um here i'm going to create a new file in the root of the project called nodemon dot json and here i'm gonna define a json array inside that array a new key called env and i'm gonna define another array for that and inside that i'm gonna define my another key which is jwt underscore key right now i can define the secret like this so i can use this key anywhere in my project all right now i can replace this hard coded secret and instead i'm gonna type process dot inv dot then the variable name just like this and i can use the same value same value here as well now we have got the token decoded and now we need to append that data to the request let's say user data so that we can use uh this value this decoder token anywhere in our controller so any other method that uses this request parameter all right so after we append in this request then we can call this third parameter we used next well what it does is it hands over the uh execution to the next middleware available well since this is a middleware we execute the code we want and we pass the execution to the next available middleware any other function and of course you can name these three parameters with anything you want it doesn't have to be the same names all right now this code block is complete and let's just complete this catch block really quick the error and if there is an error this code will be executed we need to return a response like this the status code should be like 4.1 because it's unauthorized the message should be like um let's say invalid o expired token all right so that makes more sense and we can include the error as well the error returned by the json web token package which is this all right our middleware function looks complete and we need to export that function module dot exports just like this all right now our middleware looks complete and then we need to include this middleware in our appropriate routes i'm gonna open up the post route file here let's import our middleware i'm going to define a new constant check oat lure now i am going to use this middleware in certain routes just like our save route only the authenticated users can save a post so here just like this so this is the function name we used in our middleware all right now we need to use this middleware in our patch route and also in our delete routes as well because those routes needs to be protected as well because only an authenticated user should be able to delete or update the post alright so this looks complete and let me open up the terminal i'm going to start my application npm start looks like we don't have any errors nodemon started and let me open our api testing client now i'm gonna open up our save post request and currently we have not included any token let's just send the request the same way we did before and it says invalid invalid expired token which means our middleware works let me generate a token by logining and this endpoint and generated the token for me i'm gonna copy this token and open up the save post request and here in this auth section i need to select bearer token option so here in this field called token i need to put my token all right now let's send this endpoint again now we have create a double successfully so which means our middleware works perfectly now let's test our other two endpoints as well update post um let's send this endpoint without the token and we get the error message which mean it works and let me include the token and then hit the request it works and for the delete post the same way and after including the token yeah the post deleted successfully so we have successfully implemented a middleware to protect our routes you can use middleware for many purposes protect routes by checking the tokens or user levels or you can use middleware for to write active logs and so much more so i hope you enjoy the video hit the subscribe button right here if you haven't already and i'll see you guys in the next video
Info
Channel: coder awesome
Views: 5,984
Rating: undefined out of 5
Keywords: node js, express rest api, Protect Routes with Middleware in NodeJS - Rest API with NodeJS and MySQL (2020), middleware in nodejs, middleware explained, nodejs middleware tutorial, protect routes with middleware in nodejs, allow access only to authenticated users, add private routes with middleware in nodejs, verify access token in nodejs middleware, block users with middleware in nodejs, coderawesome, coderaweso.me, coder awesome, coder aweso.me, node js express middleware
Id: 9EyuLacWT0o
Channel Id: undefined
Length: 13min 44sec (824 seconds)
Published: Thu Oct 29 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.