This tutorial provides a rigorous blueprint for JWT middleware by addressing critical edge cases, such as post-login password changes, that most basic courses ignore. It effectively transforms a standard authentication task into a masterclass on building resilient, production-grade backend security.
Inmersión profunda
Prerrequisito
- No hay datos disponibles.
Próximos pasos
- No hay datos disponibles.
Inmersión profunda
Authorization - Part 1: Read Access Token | Node JS + Express Course with MongoDB | Part #154Indexado:
*🔹 Video Title: Authorization Part 1: Read JWT from Header & Create Middleware | Node.js + Express* *📽️ Description:* Welcome to Part 1 of our Authorization series in the Node.js + Express course! In this video, we start implementing authorization by learning how to: ✅ Read the JWT access token from the request header ✅ Understand how the Authorization header is set by the client using the Bearer token format ✅ Create a reusable middleware called isAuthenticated to validate incoming requests This is the first step in securing your API endpoints and ensuring only authenticated users can access protected resources. Perfect for developers building secure backend systems with Node.js and Express. 👉 Like, comment, and subscribe to follow the complete Authorization series!
In the last few lectures, we implemented authentication in our express application by allowing users to create their account and also by providing a login functionality. Now from this lecture, we are going to start working on authorization in express app. So as we have learned in the introduction lecture of this section, authorization means what a user is allowed to see and do once he is authenticated.
Now for authentication whenever a user is successfully logged in or he has successfully signed up we are sending a JSON web token to the client and this JSON web token will act as an identity proof for the loggedin user to access any protected route. So now we are going to implement the authorization functionality where we will allow logged in users to access protected routes but we need to restrict anonymous or we can say not logged in users from accessing the protected routes and that's what we are going to implement in this lecture and in next coming lectures.
Here I'm in VS code and here let's go to this routers folder and let's open hotelser.js.
And here we have defined some routes for hotel resource. Now let's say we have this get all route to get all the hotels. Then we have this create route to create a new hotel. We have this get by ID route to get a hotel detail by its ID. And then we have this update route to update the details of a hotel and this delete route to delete a hotel. Now any user whether the user is logged in or not he should be able to view all the hotels. So this get all route we are not going to protect it. Any user even the anonymous user should be able to access this get all route. In the same way this get by ID route since an anonymous user should also be able to see the hotel detail. We are not going to protect this route as well. But an anonymous user should not be able to create a new hotel or update a hotel or delete a hotel. So these are the three routes which we are going to protect for hotels resource. We also have routes for getting the featured hotels, getting hotels by city and getting hotels by type. So these routes also should be accessible by any user whether the user is logged in or not. But for the hotel's resource, an anonymous user should not be able to create a hotel, update a hotel or delete a hotel. So we are going to protect these routes and these routes should be accessible only by a loggedin user. A non-logged user that means an anonymous user should not be able to access these routes. They should get unauthorized response.
Okay. So let's see how we can do that.
For that in the O controller I'm going to create a middleware function. So let me create a middleware function here and we are also going to export it. So on the exports object I'm going to create a function is authenticated because this function is going to check if a user is an authenticated user or not. So here I'm going to create an async function and since this function is a middleware function this function is going to receive the request object the response object and the next function and since it is an async function we can also pass this function to catch async function so that if there is any rejected promise inside this async function that will be handled by this catch async function. So this we already know from our previous lectures. Now inside this function we are going to do five things. The first thing which we are going to do is we are going to read the access token from the request header.
So when a user logged in, he has received an access token and that access token will be used as an identity proof for the logged in user. So whenever the loggedin user is going to make a request to a protected route in the request header, the client also needs to attach the access token. So first we are going to check if in the request we have an access token or not. If we do not have an access token attached to the request header that means that request is not made by an authenticated user. So in that case we are not going to allow the user who is making the request to access the protected route. But if the access token is present on the request header then we are going to check if the token is valid or not. That means either the token is not expired or it is not tempered with. So here we will check if the token is valid or not.
And a token will be valid if it is not expired or if it is not manipulated.
If the token is expired that means that token is not a valid token or if the token has been tempered with if it is manipulated in some way in that case also the token is not a valid token.
But if the token is valid token in that case next we are going to check if the user who is making that request if that user exists in the database or not because it is possible that when the token was issued if you remember the JWT token which we are generating while sign up or login for that token the validity is 30 days that means within that 30 days the token is a valid token only after 30 days the token is going to expire. So let's say when the user had logged in at that time a token was issued for that user but after few days the user deleted his account or maybe the admin deleted the user account. So in that case the token is still valid.
The token has not expired but the user for which that token was issued that user itself is deleted from the database. So in that case also we should not allow the client to access the protected route. Okay. But if the user also exist then the next thing which we are going to check is we are going to check if the user has changed his password after login.
Here also since the token has an expiry date of 30 days when the user logged in and when the token was issued for that user after that if the user has changed his password in that case also the token should not be valid. The user should not be able to access the protected route.
In that case, we should ask the user to login again with his new password and generate a new JSON web token. So that will be the fourth check. And finally, if everything goes well, if the access token is available on the request header and if the token is also valid and if the user is also existing in the database and he has not changed his password, then finally we are going to allow the user to access the protected route.
Okay. So if all these checks are successful then we are going to allow the user to access the protected route because in that case the user is a valid user. He's an authenticated user and he should be able to access the protected route and to allow access to the protected route all we have to do is we have to call the next middleware in the stack and in this case the next middleware in the stack should be the route header function. And now whichever route we want to protect for that route first we are going to call this middleware and from within this middle layer if everything goes well and this next function is called it should call the route handler function. So for example again if I go to hotels router.js file there I want to protect this create route update route and delete route. So here first of all we are going to require the o controller.
So I'm going to create a variable. I'll call it as O controller and to require the O controller we going to use this require function and to that let's pass the path of the O controller. So in the controllers folder we have O controller and from there we are exporting this is authenticate middleware function or I'll call it as is authenticated. Okay, let's save the changes here. And now before calling this create route handler function, before that we are going to execute the is authenticated route handler function. So on the O controller, I'm going to call is authenticated route handler function.
And if there is no error inside this middleware function, if there is any error inside this middleware function, in that case we are going to write some logic to throw an error. But if everything goes well, if all the checks are success, in that case we are going to call the next function. And when this next function is called, that means it is going to call this route handler function.
And same thing I'm going to do for update. So there also only an authenticated user should be allowed to update a hotel document and only an authenticated user should be allowed to delete a hotel document.
Let's save the changes and before we test this middleware whether it is working or not, let's also go ahead and let's write some logic. So in this lecture we are going to implement this check where we are going to read the access token from the request header. Now when the client is going to make a request to a protected route, the client has to attach the access token the JSON web token which the client has received after login with the request header. And for that if I go to Postman and here I'm going to take an example of update hotel request. So before that let me save this signup request. Let me close this signup request for now. I'll keep this login request open because I might need to copy this JSON web token. Okay. And here let's go to this hotels folder. And from there I'm going to open update hotel request. Now remember that when we are going to make a request to update a hotel before that we are also calling this is authenticated middleware function which is going to check if the request which is made by the client if it is made by an authenticated user or not.
So for that with the request so here let's say I want to update this hotel document with this ID and there I want to change the cheapest price to 90 okay now when I'm going to make this request with this request I'm also going to attach a header currently for this request we do not have any header but here for this request we are going to add a custom header called authorization So basically this authorization it is a custom header which we are creating and this is also a standard name for the header when we want to send a JSON web token with the request header. So here we are basically attaching a header a custom header to the request which we are calling it as authorization.
Now to this authorization header we need to assign the JSON web token of the authenticated user and we need to assign it as a beer key. Now we use beer key because we are the one who poses this token. So anyone who poses the token can use it to access the protected resources. And to specify a beer token, first we need to use this key beer, then a space, and then the access token. So access token, let's say here the logged user is John Smith. So since this user is logged in, he's an authenticated user. And that's why for that user, we have this JSON web token. So we are going to copy this JSON web token this access token and [snorts] we are going to pass it as a beer key for this authorization header with this patch request.
Okay. So remember that in order to send the access token with the request header we create an authorization header which is a standard name. You can also call it something else. But the standard name to call this type of header is authorization.
And to this authorization header, we assign a beer token. So we use the beer keyword followed by a space and then the access token. So this is how we are going to send the access token to the server to our express application with the request.
And now from our express application we are going to read that access token from the request. Okay. So here first I'm going to create a variable. I'll call it as test token.
And we going to read the token from the request header. So on the request object we have a header property.
Actually it should be headers. And on that we are creating a custom header called authorization. So let me copy this and we are going to access that authorization header. Now if this authorization header is not present on the request headers in that case this expression here will return undefined and undefined will be assigned to this test token.
So what we are going to do is we are going to check if this test token is not a falsy value. if it is not undefined.
So if this test token is not undefined, it has some value then we are going to check if that token that means the value which is stored in this authorization header if it starts with B error. So for that on this test token I'm going to use a JavaScript method which is starts with. So this is a string method and here we are going to check if the value in this test token basically the value returned by this authorization header if it starts with B error. Okay if it starts with B error that means we have an authorization header attached in this request header. So we are going to read it. So here I'm also going to create another variable. I'll call it as token.
Okay. And initially I'll assign it with empty string. And in here I'm going to reassign it. So here let me use let keyword because I want to reassign it.
So here we will say token equals and we know that this authorization it is going to return us a beer key that we are storing in this test token. So from that test token we are going to split it by a space. Remember that the authorization header is going to return a sring value starting with beer space and then the access token.
Okay. So here we want to extract this access token string. We don't want beer and space. We are just interested in the access token which we have after beer key. Basically we are interested in this value. So we want to extract that value from this test token. So what we are doing is we are splitting this string by a space. So in that case the split method is going to return us an array.
In that array the first element will be error and the second element will be this access token. Right?
So here this expression is going to return us an array and in that array the first element will be P error and the second element will be the access token.
So we want to get that access token. So we know that this access token will be present as the second element in the array which will be returned by the split method. So we are going to get that element and the second element will be present at index one. So we are extracting that value and we are assigning it to this token.
And now here let's simply go ahead and let's log that token and let's check what it stores.
Let's save the changes and let's go to postman and from here let's go to body and there I want to change the cheapest price of this hotel document with this ID to 90. Let me make a request.
Okay, here we have an error and it says price of a hotel cannot be less than 100. That's correct because we have added this validation. So let me change the price to 120. And if I send the request, you see we have received a response and here the price should have changed to 120. But here we are not interested in that. Let's go to terminal and there we should have the access token logged but I don't see it there.
Let's see why is that. Let's go back to VS code.
Okay, here this header it should all be in lower case. So it should be authorization.
Even though here we are specifying the header in upper case when we are going to read this header we should read it all in lower case. I think that is the problem. Let's save the changes and let's verify that. So we do not have any error. Let's go back to Postman. And now when I send the request let's go back to terminal. And now you will see that that access token is logged here. Okay. So in this way we are able to read the access token which is attached to the request header.
Now if I go back to postman and if I don't specify this authorization header.
So for that I can simply uncheck this.
And now if I send the request let's go back to terminal. And now you will see that an empty string has been logged here. Why? Because in this case this authorization header does not exist on the request headers. So in that case it has returned undefined. So here test token will be undefined. So this whole condition will be false. And in that case the initial value of token was empty string. So here when we are logging token, it is logging empty string. If I log test token here and if I go back and if I make a request in that case for the test token it should log undefined.
So here we have received the response.
If I go back to terminal there you will see that for the test token undefined is logged and this undefined is logged because this authorization header is not present on the request headers.
But if it is present in that case we are going to extract the beer token from that authorization header and we are assigning it to this token.
Okay. So if this authorization header exist and if it starts with beer we are assigning this token by extracting the actual JWT from the beer token. But let's say if the authorization header does not exist or if it exist it does not start with Ber in that case this token will be empty string actually let me set it to null. So initially it will be null. So if the authorization header does not exist or if it exist but it does not start with beer key in that case the token is not a valid token. So in that case I'm going to check if token and here I'm going to use this not operator. Remember that this token will be null if the authorization header does not exist or if it exist if it does not starts with beer. So in that case it will be null. In that case this if condition will fail and this token will not be reassigned.
So it will be null. So if that token is still null that means either the authorization header does not exist or even if it exist it is not starting with the beer key. So in that case here we want to create an error. For that let's create a variable. Let's call it error.
And to create the error we are going to use our app error class.
And here we will simply say you are not logged in.
And here we are going to send 401 which stands for unauthorized. So this will be the status code. Okay. And from here let's go ahead and let's call the global error handling middleware by passing this error object.
Let's save the changes.
And now if I go to postman and since I have not specified this authorization header if I send the request we should get an error which says 401 unauthorized.
So since the authorization header is not available with the request we are getting this response. But if we include the authorization header and now if I send the request the request should go through and we should get a response.
As you can see we have got the response.
So here we are checking if a user is trying to access the protected route with the request if the client has attached the access token or not. So in the request header we should have an authorization header which should store a beer key and the beer key should have the access token. So if the authorization header is not present or if it is present it does not start with B error in that case we are throwing this error. But if the authorization header is present on the request header and if it starts with B error we are reading the access token from that beer key.
Now we need to check the access token which we have retrieved from the authorization header if it is a valid access token or not. That means the token should not have been expired and it should not have been tempered with and that validation logic we are going to write in our next lecture.
So this is all from this lecture. If you have any questions from this lecture then feel free to ask it. Thank you for listening and have a great day.
Videos Relacionados
Ubuntu Touch Q&A 190
UBports
241 views•2026-05-17
Learning k8s ep. 3 - The end of the VM
devcentral
102 views•2026-05-15
Iterators and Generators: Real Use Cases
jsmentor-uk
188 views•2026-05-17
TCS NQT Coding Questions Solution (One Shot) | TCS NQT Preparation 2027 | TCS Actual PYQ 2026
knacademy20
2K views•2026-05-17
The 4 Bit AI Training Trick
explaquiz
414 views•2026-05-19
Image to 3D World Workflow 👀
badxstudio
843 views•2026-05-16
Why Learn Algorithms in the AI Era
bitsandproofs
245 views•2026-05-17
NFA - Transition Diagram and Transition Table
nesoacademy
198 views•2026-05-19











