JWT Route Protection | Creating a REST API with Node.js
Video Title: JWT Route Protection | Creating a REST API with Node.js
Welcome back to this series in the last two videos we added user signup and user login in this video I want to make sure that we can also protect routes we got that token which we issue since the last video that token we can store on our
Client not want to make sure that we can use that token to access certain routes on our back-end that are protected before that we need to add protection to some of these routes first so let’s do all of that in this video time to add some protection we got our
Products and we got our order routes here right now there are some routes which we don’t want to protect for example getting all products that makes sense to be an unprotected route because if we were to create a front-end for our shop here we probably want to be able to
Present all our products even to an authenticated users the same is true for the get route to a specific product typically we want to allow the user to get more product information before he has to sign up and that maybe buy it or whatever the plan is however other
Routes like creating a new product or deleting products or changing products and maybe all order related routes including the GATT roads here are protected routes we want to make sure that not every user can access them and therefore we need some way of protecting these routes a good approach would be to
Add some kind of middleware which we can easily add to a given route that runs prior to that route getting processed to actually determine does it make sense to continue or aren’t you Afeni cated anyways so we need to add some middleware that checks for a valid token
To be there and only if the token is there and valid can be verified so it hasn’t been filled around with on the client only if that is the case we continue so that’s the plan we’ll add such a middleware for this I’ll create a
New folder in my API folder I’ll need a name it middleware you could name it off whatever you want and in there I’ll make add my check off J’s file because this is what I want to do I want to check whether the user is authenticated or not
I’ll start with module exports to export something and that something is going to be a Aero function where I get the request response and next you probably know this pattern it’s the default middleware pattern we use in Express Apps now I just want to create this
Function and export it in this file so that I can import it in my order and product route file and then use it in there to add to certain routes if you remember in the product route here we have the post route where we also have that upload
Signal middleware which will parse a file and this is exactly the same pattern I want to use we can add as many handlers as we want and they will be executed in the order from left to right so if I then add my check-off middleware here I will actually run through that
First and only continue if we succeed that’s the plan now for that will create it here now what do we have to do in this file we have to call next if we did successfully authenticate and we want to not call it we want to return an error
Instead if we did not succeed so for that we need some information from the JWT package or we need some help from that package we used in the last videos there we have a way of creating a token now there all this a verify method which allows us to verify an incoming token
That is what I mentioned in the last videos the server can verify whether a token is valid or not for that of course we need to that key we stored on the server and we need to token so let’s do just that let’s import this JSON web token package
In this file here so I’ll create my JWT constant and simply require JSON web token and then in there I will simply create a new concept which I named decoded because the verify method will actually return the decoded token if it succeeds and then I will call JWT verify
Now you might see there are always a decode method this will just decode the token and not verify it and as I mentioned in the last video the token is not encrypted so decoding alone doesn’t ensure it’s valid it just ensures its valid base64 encoding but that doesn’t help us
So decode is only helpful if you want to get to the internals of the token after having verified it if you didn’t verify it yet then decode makes no sense and verify we’ll do both verify it and then return the decoded value so here is what I’ll use
Verify and then I assume to get to token as part of the request body if we don’t well then we will always fail here and that is exactly what we want to do if we go into this middleware which we only do if we added it to a route if we go in
Here and there is no token present then we should fail because then we got note Okin right so we pass the token here the key is what we stored in our environment variables to process end and then it was JWT key in my case here I added this in
The last video and then the next argument are some options I don’t pass any special options here and then a callback you can specify so I will omit the last two values here I just want to verify it like this now this method verify will actually throw an error if
It fails so what I’ll do is I’ll add a try-catch block here I’ll try decoding the token so I’ll try this code here but if I fail then I will catch my error and in here I will then return a response where I set the status code to 401 on an
Authenticated and return a JSON object with the message off failed just like that if we succeed here in the try block though then we got a decoded value and I will eventually call Next to continue and what I also can do is I can set request user data equal to decoded so
I’m adding a new field to my request make sure to pick one which you don’t accidentally which you don’t already have so that you don’t overwrite it and now in future requests which use these map that this middle where in front of it we could extract a user data the
Decoded user data on that field now with that we get a middle where let’s now try it out and let’s go to the products file a page maybe and let’s add it to the post product route so GAD should be publicly accessible but we want to add
Our middleware to the post route so I’ll first of all import it I’ll add and you can’t set the top here check off and I will require it from middleware check off and this is now the function we’re exporting there which is a valid middleware function and now in the post
Route here I will simply add check off in front of this upload single and the other handlers so this will run first I don’t execute it I will just edit like this and Express will automatically pass requests and so on into this now let’s try it out let’s go back to postman and
Let’s create a new post request to products let’s switch to foreign data again and make sure you enter your valid data here and choose a file I added a very Christmasy file here again and let’s now simply try this out let’s now hit send and first of all go to headers
And disable this content type and hits send again and we get all failed because the token is missing we’re checking if we got a token in the body so let’s simply add one let’s first of all make sure we can login I’ll create a new tab with a post request again queue localhost
3000 slash user slash login and asked before I’ll add a header here content type application Jason and a body raw JSON data where I will set an email password combination that exists in database well again use test free at test calm and your password was tester
Now if we use that and we sent this request I get my token so I’ll copy that and now go back to the first tab where I’m setting the post request to products and I’ll add my token key here and add token as a value I now hit Send I still
Get all failed though now it can be difficult to find out why the reason is that in this post route remember we’re getting full and data were not getting JSON data now in the app J’s file we only get body parsers for URL encoded and JSON content type requests neither
Is the case here we got form data and we’re taking care about this with the upload single mail aware which simply parses form data requests and extracts the file along the way but it does this parsing since check off runs prior to this request body will not be populated
Because it hasn’t been parsed yet now one workaround of course is to switch the order here we can put check off as the second middleware if we do this and ahead send here then we do simply a continue we just fail with the creation of the uploads directory here
Because I deleted that in the meantime I would have to re-add it if I do that uploads and I had send again it succeeds and we can see the file here then so then it works this is one way changing the order yeah we can do this we’re doing some
Unnecessary work here with the parsing since we don’t check prior to it if we are authenticated and in general we might not want to pass the token as part of the request body because what do we do for get requests sure we could add it
To the URL in a query parent or example and we can’t do all of that but a typical pattern is to put the token into the header so I’ll remove this key here I don’t want to send to token like this I want to send it as part of my headers
And there’s one common header we use for this the authorization header authorization as the name implies should hold any information we need for authorizing a request and there a token is typically sent by adding bearer whitespace and then the token so the token you previously previously sent
Here in the request bodies let me copy it again and put it here after Bearer now why bearer notice is simply a convention used to indicate that this authorization header bears a token it’s basically an alternative to basic HTTP authentication so hence bearer the tokens of course the
Interesting part with this setup we don’t need to parse the body to get the token we just need to have a look at the header so in check off we now get to token from the header so I’ll first of all simply try to get my token from the
Header and I can do this by accessing request header a headers authorization if I do this let’s simply lock to token here if I now again sent my post request to create a product it now fails here because I removed the token from the from the body remember I unchecked this
Year I’m no longer sending it so it fails in the console log we see this out though so we did successfully parse the header and that of course means we can now use the token from there we just have to make sure that we don’t include the bearer and the whitespace so what
I’ll actually do is I’ll get my request headers authorization and split it by a white space I then access the first segment where the second one actually with index one which will be this part after the white space and then I can pass my token here to the verify method
All safe doesn’t go back to products and now revert the order here again so I’ll now add check off prior to trying to parse the body here and now if we save this make sure that authorization is set to your token with bearer in front of it and if I try to
Send us again it now succeeds if I change to token by for example removing the e and therefore all basically send an invalid token it fails and this is a nice middleware we can now use to make sure that we protect our routes let’s add it to multiple routes then instead
Of just adding it in front of or in our post route here I’ll also add in the patch route so before we there have our main handling function and in the delete route not in the to cat routes as I mentioned and the same in orders there
I will now also import my check off middleware by requiring this from the middleware folder check off and I will add it there to in front of all routes actually because all should be protected including the GATT routes so getting all orders posting new orders getting a single order and deleting order
Everything is now protected and now if I save this we can try it out we train can try getting products and this should succeed even if we remove that header because it’s not a protected route if I try to delete a product though for this
Let me quickly get an ID like this one so if I now add this in the URL as we have to do it for a delete request and I sent this without the authorization header I get all failed if I add the authorization header I still get it because it’s still
The invalid token so let me reverse this by adding de again now it succeeds and if I remove it just to prove this again and of course fails so this is now an option and now let’s check our orders there we can’t just try to get all
Orders if I don’t add the token it fails if I do add it it succeeds so this is how we can now use the token how we did add our middleware which we can now conveniently add to any route that should be protected and we’re using the tray WT concept for this authentication
Flow and for making sure that the client can identify himself to our server and access protected resources without the server having to store any information about the connected clients this is now true stateless authentication implemented in our restful service through JSON web tokens now with that we
Made a huge step forward we added authentication
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
welcome back to this serious
how do we verfy if the product exist before uploading the image
That's the reason I purchased Max's 8 courses on Udemy and they really helped me to excel and learn new skills.
Still watching in 2022, this is an awesome walkthrough!
thankyou
I was having an error "cannot read properties of undefined "reading path", it was because I was passing an image with a mimetype .png and in my code I was allowing only images with mimetype jpeg,when I selected a file with correct mimetype this error was resolved. Hope this helps, excuse my english.
"Unexpected token – in JSON at position 0"
welcome back to serious..lol:):)
pls I have a challenge after setting up jwt and auth route I am trying to get user details without having to get it from d front end or having to decode the token all d time on all request . am trying to get user details from req.userData in any contoller
Someone can share me link of the docs that Maxmilan talks in the begginning of the video?
I know this is kinda late but anyways Thank You soo Much for the learner-friendly approach! I've learn a lot from this course! :))
how can we use " req.userData = decoded; " from other file to get decoded data
can you post the code?
Why send "Bearer" at all if we remove it server-side?
how to protect api from csrf & xxs attck? if you store the token on local storage then its xxs vulnerable but if store it on cookie then its csrf vulnerable.
Hello Max and thank your for your great work. In the related videos you show us how to work with JSON web tokens. My question is how can we save this token and use it after we make a successfull login to access the resources of our site . Thanks in advance
Using this series in 2021, so glad I got here because I definitely got a feeling for what MIDDLEWARE is! Awesome!
hi, help please lol, im currently pulling my hair out,
every example i see of this they are using postman and manually setting the Authorization header to one token string,
how do we set the header when someone logs in without having to set this manually (with no postman)
So someone logs in and the server knows they are authenticated by their token , thanks
Is there any to put checkauth on top of the product.js file so that we need to add the method just once for all routes of /products/
For "orders" we can use:
app.use('/orders', checkAuth, orderRoutes);
Thank you very much you are awesome
amazing thanks a lot
I think this logic doesn't protect the routes and data! I can get a valid Token for my user but delete anything on the database as far my token is a valid one but has nothing to do with the data? Did I miss something?
12:31 My code doesn't work with Authorization header. I don't know why. It works only with body.req.token
and checkAuth must be placed last.
I am geetung these error , anyone can help ??????
{
"error": {
"message": "Cannot read property 'path' of undefined"
}
}
it shows an error at server as Cannot read property 'split' of undefined in check-auth.js , then how can i access the token
323 WHoop
One simple thing, you need to validate req.headers.authorization. Otherwise it will return …split(" ") is undefined. Great tuto, loved it. Keep up the good work.
what is the way to ensure that the token is sent on subsequent requests by client…i use cookie…maybe localStorage can be used…is there a better way?
this is the way to protect a route
sent post request and set the authorization and there was a response that auth failed
please help
Wonderful Series! Thanks a lot.
wonderful serie of videos, really helped a lot!
thanks so much @academind