Next.js JWT authentication httpOnly cookie (Updated video link in description)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right so we're going to be doing next chess authentication using jvt and we're going to use cookies instead of storing the token inside of local storage because we are professionals so let's get straight into it i have a nexus project here and it has an index page where i have two inputs and a button i have a use state here for a password and for changing the values for because we need to get those values so we can send them to our back end now the first thing what you're going to do is install cookie and json web token these are the two libraries that we're going to be needing to implement this to implement our own authentication so install cookie and json web token and we can continue now we want to log in our user create a token and send it put it inside a cookie and send it to our client side so we're going to be doing this with the sign function in json web token and serialize in cookie so create an off folder inside of api and then create a login js so it's going to go off api and then log in okay api off and then log in okay this is going to be our route for logging in now we also need to define a secret key this is for our jvts because we don't want to expose the secret key to anyone so when you create a env.local file you're going to need to store this basically it needs to be very private so you're going to create a secret that value here and you're going to do whatever you want here the what the the more complex this thing here is the better it is for you so you have a secret here you can name it whatever you want and we're gonna pull this so we can sign the key okay so now that we created this function we need to get the username and password that our user sent okay so most of the time you're gonna be having a data you're gonna have a database here i don't know postgresor or mongodb whatever you want and you're gonna be getting the username and the password the user which you want to authenticate from the body okay now you're going to check for example check in database if a user with this and password exists okay so when you check this if the user exists and we're going to hard code some information here for example if username is equal to admin and password is equal to admin we can continue and the username and the user is entered the [Music] the correct credentials but if it isn't we're going to respond with for example 401 and you can say invalid credential okay now here's the the most important part we need to create a token that we're gonna sign okay so we're gonna call the sign function we're gonna make it valid for 30 days okay so this is seconds times 60 times 60 times 24 times 30 okay and you're going to have some payload here okay so for example if your user needs to have i don't know his date of birth you're going to say date of birth and then whatever you want here okay it's going to be from your database so in our case we're just going to hardcore the values for example we're going to say the username and it's going to be the sent username and this here is the secret it's this secret here that we we need to use and it's we get it like this so in our c in our constant here secret we're gonna fetch it from here from our env variable okay so now that we have our token we need to create a cookie so we need to serialize a cookie and we're going to be doing that with the serialized function from cookie mp a package and we're going to say serialized is equal to serialize and we're gonna give it a name so for example our site jvt this is the cookie name we're gonna pass it the token and we're gonna give it some values here that are that are needed for this to work okay so this is hd http only true you need this because we don't want someone else to mess with our cookie on the client side because we don't want anyone to access our cookies using javascript okay we need this this http only true you can read up the documentation and these other things i'm just going to explain the max age and this is basically when the cookie expires so this here and this here should probably probably be the same if you want your back in working because if this expires you cannot send it and if this expires you will be unauthorized basically because the token will not be able to get verified and now we want to set headers so we're going to say set header and this header set cookie is the one that we're going to be using okay so in our set cookie header we're going to be saying serialized so this means that when we send the response that cookie will be set in our browser and no one else from javascript can access it it can only be used to send it can we only use it can only be appended to a request or something okay and now we want to say status 200 and let's say message is success okay now we reload the page we go to our expect inspect element and let's go to our index we got the username and password from here and now we're gonna make request and i installed axios you can do whatever you want you can send the request however you like but i'm using axios so i'm going to say const user is equal to a weight axios post and we're going to send it to api slash off slash login okay and we're gonna send our credentials now let's log the user and let's see what's happening okay so we go we enter some invalid info and request fail with status 401 okay let's see what's this but if i say admin admin and i log in the request is good you see success so if we are invalid it throws an error right it should not be throwing it like this i think but let's see runtime error unauthorized right right api 401 on authorized uh let's let's remove this just so we can i want i want to show you guys that it's working i don't want to mess with status code right instead it goes right now okay so it says invalid credentials so now when we log in with our provided credentials we log in it says data is message success and now when we go to our application and we go to our cookies you can see that our site jvt it's this okay it works and this is the value of the jvt it also has an expiration date size http only and everything else and this is the the main thing we cannot access this if it's from javascript so that makes us safe now we want to be using this cookie in for example let's authenticate our user let's check if we can actually access something with this so we're going to be creating a route to site api so we're going to say for example get user let's say user.js okay you'll get a export default async function okay let's disable yes okay let's disable this because it's anonymous function i don't want it to i don't care about it because we're doing a tutorial here we're not creating a project and now we want to protect our route basically we don't want anyone else to mess with us without our explicit permission so let's say we can get some users here so we need to get the cookie okay we're going to be sending this and we need to get and check if it exists so we're going to say cookies it's easy to request so this basically gets the cookies from the request and now we can cancel that let's get our jvt and say cookie is that our name so it's our site jvt so you do not give values like this this ones you give it strictly letters and now we can cancel that bug jdk and let's say the request is successful always i just want to show you that we can read the jdt and that it's there okay so let's reload this request and let's create another button here to get some data okay so user now when we click it we want to call a function handle get user for example okay we can create handle get user okay i keep keep doing this okay so let's say we want to send the request there so we're going to say user xio so we're going to call user instead of login okay we don't need to send any credentials and this is a get request okay and let's cancel that log actually we don't need to cancel our plug anything we can just send the request okay so we reload and let's see this being displayed here so we can load it here compiling api okay that works we when we call the user now okay there it is okay this is the token now we have the token and now we can actually do something that we want so we we can say if jvt if it doesn't exist we can say let's.json and we can say message invalid token okay but if everything is all right we can just say for example data top secret data okay so now when we send the request here we need we should log it we should log it actually so we're gonna cancel.log user okay we reload the page now when we send it you see top secret data because we have the cookie inside of here okay so let's say i delete this cookie i reload the page and i say user and we have data invalid token because it checks if the cookie exists so you see invalid tokens okay you should probably change the status to 401 or something but that's up to you now if we log in we logged in okay we get the data it says success and now when we try to get the user it says top secret data so this part here worked so that's it it's it's not hard it's better to use this instead of putting the cookie inside putting the jvt inside at local storage because anyone that executes a script on your browser can basically steal your cookies still you're still your jvt if it if he has access to cookies and there's one more thing you need to know and that's you want to log out okay so it's not really hard you can just create a new route in auth call it logout.js we're gonna export a default basic function again it's gonna have a request a response i'm just gonna disable this warning okay and again we want to de-authenticate the user basically okay how can we do that well we can just check if the user has the jvp cookie we're going to say jbt is equal to cookies dot our site jbk and we can see if jvt so if we have the cookie let's just check first if it isn't you can say rest.json message bro you're already you are already not logged in okay and if it is we want to just clear the cookie right it's it's totally simple so if gdt does exist we're just going to set headers again and we're going to say the same thing here in login log out here serialized but you see it's rsi jvt and my max age that's not important but we have nothing to put in here okay so we're gonna say null instead of token and we're gonna import the serialize function from cookie and now we're just going to do the same thing so we're going to say let's start header set cookie serialized this cookie and we're going to say json successfully logged out okay so now when we reload go to our application there it is let's create a log out button log out on click we're gonna say handle out i don't know if it's two words or one i don't care okay constant logout async we await a const user logged out or something it's not important wait axios dot now you can get or post this i'm just going to call it get and we can say api slash off slash log out because now we want to log out okay and now we can console.log user and now we reload okay we have the cookie oh yeah i'm i'm very done this this part here is not important it's important that the max age is minus one so it gets cleared so let's see we let's say we authenticate ourselves admin login we have our cookie here and when we call log out it gets removed because this max age expires and the good thing about this is that the max age ex it clears the cookie instantly so you don't need to worry about anything so let's say we for example we have our cookie that's that's valid for five seconds okay we can log in we get the cookie it's valid for five seconds all right so next time we go we reload we reload the page it's empty so it it handles itself you don't need to handle anything else and create hooks for yourself for local storage or anything else so now that you logged out you can call the user and invalid token it won't allow the whoever it is to access the protected routes so that's it that's the entire part the main part of jbt authentication using cookies http only cookies
Info
Channel: Tenacity Dev
Views: 29,074
Rating: undefined out of 5
Keywords:
Id: T6fRWZWrJzI
Channel Id: undefined
Length: 17min 46sec (1066 seconds)
Published: Wed Jan 19 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.