Adding User Login & JWT Signing | Creating a REST API with Node.js
- January 1, 2024
- Posted by: MainInstructor
- Category: Go JavaScript Node
Video Title: Adding User Login & JWT Signing | Creating a REST API with Node.js
Welcome to this video great to have you on board in the last video we added users sign up so the functionality to create users in this video I want to make sure that users can also lock themselves in and get such a token I was referring to in the last video the token
Which we then need to attach to future requests which reach our protected routes in our back-end we don’t have protected routes yet we’ll add these later but for now let’s make sure we can get such a token at least so that is what we’ll focus on in this video
Time to you create some tokens in our user routes file we got a sign-up route now I want a second route before I delete users where I also handle post requests but to slash login and the idea here is to all to get email and password
But not create a new user but instead have a look at the database and see if we got a fitting user and if we do then actually create such a token so here first of all I’ll create response request response and next and the goal
Here will be to see if we got a user so I can use my user model and simply find any user for a given email address so we’re email is actually equal to request body email and that approach is pretty similar to the sign up route where we
Also find such users in this case to make sure we don’t create a new user for an email that has already been taken in this case down here in order to lock the user in so here we then have X act to get a real promise with them and catch
And now for caching I’ll use my default error handling code and yes we could outsource this into a separate method I might do this later for now let me stay to this more where both but also understandable way of coding this now the then block is of course interesting
To us because they’re Estelle’s where we get our user and to be precise we should name this users because as you learned this will be an array it’s just an empty array if we got no user and I’m naming it user because it will at most be one
User because we prevent the creation of duplicate entries due to our check here in signup so I get my user array and therefore first of all I’ll check if user length is smaller than one so if we got no user if that’s the case then I
Want to return a response where I set a status code of 404 and basically tell the user Ted login fail however this might not be the best pattern because what we could do is we could send a JSON response where we send a message like mail not found user doesn’t exist
Whoops doesn’t exist like this the issue with this approach is that we open our app to some kind of brute-force attack users could now just try out different email addresses and they will at least find out which ones are there and which ones are not so once they get a list of
Available email addresses they could focus on these two then get out the password or things like that so this might not be the best pattern not as super big flaw if we add it but also not great and can be a big flaw so let’s not do it like this instead let’s just
Return for a-1 which simply means unauthorized and I’ll also simply return off failed which could fail because we got no email or because the password is wrong so that’s the first check now let’s assume we make it past this if block here so we don’t return this response and therefore this code gets
Executed now we found the user the next step is to make sure that the password sent with the request matches the password in our database the thing just is we do hash our password here with beak Ritesh and in the last video I mentioned that we can’t reverse this so
How can we match the new password which is coming in plain text queue the password in our database if we can’t rebuild it well be crypt of course used a certain algorithm for hashing the password and we basically have some kind of way of comparing values even though
They’re hashes won’t be the same just by making sure that a plaintext password which we hash again with the same algorithm in the end yields us a comparable hash so this is a check this package can do for us and you can dive into the be trap documentation on the
Get up pass a repository to find out this works here with this compare method for this we need to pass the plaintext password and the hash we want to compare it to and it will return true if it basically finds out yeah both passwords were created with the same algorithm the
Same key and therefore they are the same passwords even though the hashes don’t match so this is what we can do here so in my part here after checking whether we got the email I’ll use be tripped again and call the compare method and first of all passed request body
Password here plain text password and then the hash which is of course part of the user we retrieved so user and then here we can simply access the first element and by the way and alternative to find would also be find one this would ensure that we don’t get an array
But just one user I’ll just stick to this general syntax but you could definitely use find one so here we have user is zero and this is the only user we found this user will have a password field we stored this in the database because our user model has a password
Field now with that we can compare these two and now the third argument here is a callback where we get an error or a response now our error is not returned if we can’t compare these it’s just an error we get if the comparison generally fails
So if we got an error here I simply also want to return off failed don’t need to pass more information than that if we don’t have an error I’ll check if response because of that excuse we shouldn’t name this rest because that again is a rest object so let’s name
This result so I’ll check if result and as we see in the official doc this is just true if it succeeds or false if it fails so what I can do here is I can simply check if result so this will be true if it’s exceeded so if the password
Is the correct one in this case I will return a response where said status code to 200 and then I returned my response where I say all successful and of course the token is still missing here I’ll come back to this I also need another response here at the
Very end if we don’t make it into this if block here then we return all failed because then the password was incorrect and we always return the same error code and message to give no indication about whether authentication failed because the wrong password or an incorrect email
Address and with that we get this setup we should now be able to give us back to Soph successful information let’s now save this and try it out again back in postman I did create a user with test free at test common to test for password
In last video so let’s now target slash login which is the route we created here and let’s send the same information and we should get back off successful now if I change the password and add one extra art we get all failed and the same if I
Enter a password and email which doesn’t exist we also get all fails then and if I reword this to a valid combination and again as successful so this is working as it should now we’re not done yet though we want to return such a token don’t we now for that will add another
Library to our project note JSON web token it’s a library that will do this token generation and signing and so on for us which of course is a bit of a more complex process and we simply have to install it and then follow the usage instructions down there so to do that
I’ll quit my process and run NPM install JSON web token I’ll also add – – safe to add an entry to package JSON and now this will execute and we’ll add this token to our project just as a packaged or project I’ll restart the server thereafter and now how do we use that
Now you see here we got a couple of methods like JWT sign and signing actually is what we need to create a signed token there you’ll see we pass a payload so some data we want to pass into the token we then pass a secret key so that is the
Key which only is known to the server and we also can pass more options and a callback that is executed once the signing is done and then the options you can choose the algorithm though I will keep the default change how long the token is valid this shouldn’t be too
Long for security reasons because the token is stored on a client and if the client somehow is insecure and someone steals to token there he got full access to your API so you want to make that hook and short left and these are a couple of harbor things you can define
And add the default should be fine all tweak expires in though and I will also make sure that we will sign the token to begin with so you can also see some usage examples down there to create a token let’s first of all import this package I’ll name it JWT and require
JSON web token that’s the package we just installed and then in my login route here if we got a user so here we return off successful I will actually use JWT and call the sign method now here first of all the payload what do we want to pass to the client
Maybe we want to pass the user email address and ID certainly not the password even though it’s hashed but don’t do that so I will add an email here email key and this will of course be my extracted user email so I can simply access user 0 which is the user
We got from the database and there the email field and now the same for the ID user ID can be user 0 and then underscore ID so these are the two values I want to put into my JWT so in my JSON web token then we need a private
Key and I’ll again use an environment variable for this so I’ll add it to my environment variable file there along of my or next to my Atlas password I’ll add my che WCET key and I’ll name it secret here obviously you would typically use a more elaborate string than that but I’ll just
Use that here and then I will use it here too as a second argument I’ll access process dot and dot JWT key so that environment variable we just added now let’s continue adding arguments here the next argument are the options so I’ll put this into a new line here and
Then another new line will be a JavaScript object where we can define the options of this signing process and here I’m interested in the expires in field and this can be set as you can see in the documentation to a value in seconds or a string describing time
Spans like one hour and one hour is a good duration for security reasons and finally the last argument here is a callback where we get our token you can however also omit this callback and just assign it to constant like I do here token and it will then run synchronously
And give you that token and with that we can return the message but also the token here which is stored in this token constant and now if we restart the server since I changed the environment variables if we go back and we again login for this valid email password
Combination I get back off successful and this token now if we copied that token and I go to channel ut dot IO a link to which can of course be found in the video description but I guess the URL also isn’t that hard there we can
Scroll down and copy in our token and this will now give us a decoded value because remember it’s not encrypted it’s just encoded in a base64 string but it’s not encrypted and this is what’s inside our token the email address and the user ID expiration information the algorithm
Which was used and some verification information which the end will be used by the server to verify it and if we were to change anything here like let’s say changed email you will see the token on the left also changed and therefore it wouldn’t be verifiable by the server anymore
You see that the verification the blue part here switches if I switch that so that is what ensures that our token stays valid and we can’t fiddle around with it so this is how we now add a token and return it to the user to the client in the next video we’ll actually
Use that token to then also send it with requests to resources we want to protect you learn how we protect such resources and how we can verify the token
-
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
Not to doubt your editing skills but on a pc, we can go foreward and backward only 1 frame by pressing "." and "," and i noticed that for just 1 frame your creds are visible.
bro have come here to make hackers unemployed
Thing which makes this course different from other courses is that it explains every basic code snippet the instructor types or thinks/plans , Not like I typed a line of code and you are responsible to learn that on your behalf
I followed, but postman return 404 when Im reaching to /login. I wonder what I missed. damn. Anyway..great tutorial series!
At 12:00 the mongo atlas passwd is visible tho
Is it ok to have a GET method for signup and login?
I have a question. It's based on things that I heard that may be true. So sorry 😒
13:06 – I'm getting this TypeError: Cannot read property 'password' of undefined. Can someone please help me? BTW, these are great videos on rest api. Thanks Max 🙂
11:50 you got a leak
Sir,
Thanks for sharing the knowledge. Learnt a lot from your courses till now and will continue to do so.
You are the best instructor.
Stay blessed Sir !!!.
Thanks you so much. this 14.37 min was very productive.
this series is amazing it's simple easy and really useful thanks a lot
What is nodemon.json file ? , what is purpose & how ro create ?
Anyone can help me !
You forgot to blur out your Mongo Atlas password at 12:01. You are WELCOME. 😛
If you do have more than 1 user how would that change your code ?
how hw added nodemon.json file and when does it contain environment variable please help at 11:26
You're amazing! Thank you sooo much!
Max, this is great. But i donta understand one thing. Can u explain me the difference betweee request.body.email and request.params.email. Thanks a lot
Help please
suppose i take a valid jwt, decode it from the site (13:36), generate a new jwt with bogus email and userId BUT i keep the seever key same (in this case "Secret"), it would be authorized by our api since the key matches, won't it? please help
Bro, You are a great Teacher.. Hats off.
Please throw some light on this:
Lets say I am using this login routes integrated to my application and once user logged in I want him to redirect to a route lets say /home which is a protected route only logged in users can access this but now I am not sure how to send token via headers or body while redirecting to /home inshort I want to block users who are not authorized for this route with JWT.
PS. I can add middleware in /home route but neither header or body has that token.
I want to ask 1 question
if we prevent user from login brute force attack to do not expose the email or username.
What if an attacker tries to on forget password section
there he can easily try to get a valid email .
If i am wrong then kindly correct me.
Thanks for this great tutorial, what if token is expired? how we will re-generate.
Max is awesome teacher…best Angular Course in the world in Udemy <3
for anyone who cares:
I added an else clause to the if (result) with the same code as de if(err) because the error kept being undefined, so if the password doesn't match, the result is false and the 401 status will be returned
just in case anybody faced an issue with the error- 'private key must have a value ' even after adding the JWT_KEY env variable in nodemon.json, please do restart the server, so that 'process.env.JWT_KEY ' variable is recognized which otherwise would hold null or undefined value.
I tried this tutorial why invalid signature on jwt.io
I've always wondered. Why do you always use exec() and then() when they both return a promise?
12:00 bro you revealed your password. be carefull
hy, thanks for your effort, im trying to follow you but after installing jsonwebtoken I got the error : "DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead. " ,I can't figure out how to solve it .
in the bcrypt method this works for me:
bcrypt.compare(req.body.password,user[0].password,(err,result)=>{
if(err) throw err
if(result){
return res.status(200).json({message: 'Auth succesful'})
}
else{
return res.status(401).json({message: 'Auth failed'})
}
})
Have declared JWT_KEY inside the nodemon.json file, but when calling it into user.js where const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn: "1h"
}
); — it got an error there said that "Error: secretOrPrivateKey must have a value"
There is somewhere I can find the complete code?
You're an absolute angel. Thanks for this.