Svelte Login using Access & Refresh Tokens

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Nice mate, do you have a text version going along ? I'm too old to understand the attract of coding videos.

👍︎︎ 6 👤︎︎ u/jeankev 📅︎︎ Feb 10 2022 🗫︎ replies

This seems to fill a hole in the realm of Svelte tutorials. Auth is always hard for people to wrap their heads around. Nicely done!

👍︎︎ 3 👤︎︎ u/hellobritishcolumbia 📅︎︎ Feb 10 2022 🗫︎ replies

Refresh tokens should only ever be used in SvelteKit or stored in the backend, not in a client side Svelte application.

👍︎︎ 5 👤︎︎ u/Cjimenez-ber 📅︎︎ Feb 10 2022 🗫︎ replies

Perfect! Just what I needed.

👍︎︎ 2 👤︎︎ u/[deleted] 📅︎︎ Feb 10 2022 🗫︎ replies
Captions
in this video we will log in using access and refresh tokens now i'm logged in and when i inspect the page i'll go to the network tab and i will refresh we can see that the first time we request a user and we get unauthenticated because we don't have an access token then we call the refresh endpoint that we get this access token and the third time we get the authenticated user with the better token in the headers so let's learn how to do this before we start building it up i would like to remind you that this video can be combined with other videos so if you want to use any of these backend frameworks and more because i don't know how many frameworks i will add in the future i provided some links in the description of this video now let's build the app we will start with a pre-built zvelt app that contains three components one is the home component where we show just the message you are not logged in the login form the register form and in our app that's weld we have a header and we add these components into a router using swelt spa router it will look then like this so this is a home component this is a login component and this is the register component also i'm using bootstrap and i added some styles so you can find this template in the description of this video make sure also to have a back end running and now let's make the register form work first we need to install a package called axios npm install axios but the latest version of axios doesn't work well with this weld so for the moment i will use this version 0.21.1 you may try the latest axles version but currently at the time of this recording the latest version doesn't work so i will add here script and for each input now i need to add a variable so i will create a variable let name is equal to an empty string so i will also initialize them email is equal to empty string and password is equal to empty string and now i will bind these values to the input to bind them i will use bind column value is equal to name like this and i will do it the same for the other values password so now every time we change the input these values will change and if we change all the values and we type submit we want to call a submit function which i will add it now submit and this function will be called on submit here and this will be the submit function that we want we also want to prevent default uh before i add prevent default when we submit the form it will refresh the page as we can see uh not sure if you see it on the browser but i added the we added the question mark here because the page was refreshed so for that to prevent that behavior we need to prevent default and when we click right now i'll try it now submit we can see that we are not refreshing and we didn't add that question mark and now let's submit the form so let's import axios from axis and i will make this function asynchronous here i will await axios will send a post request to http localhost port 8000 api slash register and the data that we will send is a name as the name like this but since the key and the value are the have the same name we can put it like this email and also password so this is the request and if this is successful we want to redirect to the login page so i will import here push from zwelt sp router and when the request is successfully completed we will wait here push to the login page and that should be it now let's try to register our user so i'll register this user and when i submit if i redirect to the login page which i do it means that everything worked fine and now we registered our user let's login with that user and i'll do it like this i will copy the whole code here and i'll replace it in the login as well file why because it will be almost similar because i need only to remove the name here i'll change this to sign in and i don't need the name here i can remove the name variable and when it's finished i'll push to the home page and this is api slash login so now it is uh almost completed because for the login we need to get an access in the refresh token and we have to use two different ways of getting them for the refresh token it will be retrieved in the cookies we need to add another option here which is with credentials to true so we need to add this option every time we want to get cookies from the backend and this will get that cookie and the rip the access token we will get it via the response here in the response body and first we can check if response that status is equal to 200 which means that the response is successful and i will push to the home page when the the response is successful and if it is we want to get the access token and we want to add it to the headers and the access token will be inside response.data that token will be the variable that we want and how do we add it in the headers so i'll cut this value we have to use axes now so axis defaults headers common so we will add the common header for every access request we need the authorization header and this will be equal to bearer with that token so now every request will have the same authorization header and let's see it on our browser so first i will inspect i'll go to application cookies here and we don't have any cookies yet so if i try to log in with the user that i just registered and i submit we will see that we will get a refresh token cookie so we got that value it is http only also and when we go to the network we can see that the first time we won't get so how do i close this the first time we won't get a better token here because it was just set so we have to log in again with the same user and the second request we can see uh it is here authorization bearer and this is the access token so that should be it this header is added for every request and now in the home component let's get the authenticated user here first i will import on mount from the weld because to get the authenticated user we have to request access again so let's import also access but we cannot do it here directly that is not recommended we have to use on mount so every time we want to send request in the beginning we have to use on mount because it will run after the html has been rendered and i'll make the function inside asynchronous and here we will get a response from await axios get the authenticated user and if the response that status it is 200 then we want to display the message i will do it like this hi and inside i will put the response that data is a body and the name is the name of the user because the response that data will be the authenticated user also i made a mistake here this is http localhost port 8000 api slash user because later we will change it to just user for the moment we need to keep the long url and let's test it now on the browser it says you are not logged in there are two cases that we get this either the token has expired because it lasts for 30 seconds or we refresh the page and we lost the access token to get to the authenticated user directly we have to log in immediately and as you can see we successfully authenticated but if we refresh we will lose the access token and we are still not logged in so when the access token expires or we lose it we need to use our refresh token to retrieve a new access token how do we do that we will do that via axios interceptors so let's create a directory here i'll call it interceptors and inside i will create a file javascript file access.js i will import this file here interceptors axios.js and inside that file first we need to import access and then we need to set the axis that defaults base url will be equal to this prefix here so i'll cut this prefix and i'll paste it here so this will make our access request look better for example this will be the register request and this will be the login request so now they look better because they will all have this prefix and now let's add the other part which is the interceptor so we need to add an interceptor for every response so we can add an interceptor in the request or the response in our case we need an interceptor for the response before i write any code what are interceptors interceptors will stand between requests so we can do extra stuff once a certain response happens so that is the functionality and the first case is where when the response is successful and uh in this case we don't want to do anything so we get the response and we just return it in the second case is when we have an error and for the moment i'll simply return the error also and this interceptor for the moment does not do anything so we can see our browser it will work the same we need to add here a condition once the if error that responds that status it is 401 so this is the case when the user is unauthenticated when the token may be expired or removed if that is the case we have to try to send a request so i will make this synchronous we'll get a response here it will be equal to weight axis we will send a post request to the refresh endpoint so we want to try to refresh the access token we will send an empty object because we don't want to send the any information but we need with credentials to true here also because in order to get a new access token we have to send the cookies also and the cookies are not sent by default we need to add with credentials to true to send them and we will get a response if the response that status it is 200 it means it worked and we get a new access token for this so when we get a new access token i will go to login that's weld and i will copy this code here we have to set that new access token to the headers like like we did before and we have to redo our previous request how do we do our previous request error that config contains the information about our previous request and here we will simply return access and inside we will add error.config so this return in the end it will redo our previous request and that should be it if we check the browser now we can see that we are getting the authenticated user and if i refresh now we can see that the first time it fails we get unauthenticated the second time we call the refresh endpoint and the third time we get the authenticated user so this is how it works every time we lose or the token expires we will refresh our end point still is not completed yet because it has a once a small error we will show that error once we add the logout button here in the home component so so this message here i'll paste the logout button so this is just a normal button can we show it here so this is the logout button it will look like this and when we click we want to click to a logout function which i will add it now logout and maybe we have to change the lang to typescript here not sure why the first time we have a problem so we have this function logout where we need to call again axios so we need to send access post to logout we don't need to send any data i will send an empty object but we need with credentials to true because this request will delete the refresh token and that's it so after we finish uh i'll go to login i'll copy again this uh header here i'll paste it and this time we'll set the authorization header to empty because we logout and in the end we will also push so don't forget to import a push from sba router to the login page i'll copy this and i'll do it the same here if when when we get the authenticated user if the response is 401 we will also go to the login page here as well and that should be it so now when we try logout we expect to be redirected to our login page which we do and also as we can see we removed our refresh cookie here so that is removed as well but now we will have an error if we go to our home we can see that the refresh endpoint is called a lot so i have to stop the server and i have to restart this so why is this happening so i will restart it again here this happens let's go to the interceptor because when we log out we will get the response status 401 when we get the user and then we will call the refresh endpoint but the refresh endpoint will still return 401 and we will go here again and we will call the refresh endpoint again and this will be an infinite loop so this was the small bug that i was talking and to fix this we have to call the refresh endpoint only once and to do that we need an external variable i'll create here a variable refresh is equal to false and if the response that status it is 401 and we haven't refreshed then we can refresh but we need also to set refresh to true because when we call refresh here and the refresh endpoint will return 401 it won't go here again because we set the refresh to true and we will go here where we will set again refresh to false again here and that should be it so now if we go to the home we can see that the user will be called it will return 401 and then we will call refresh 401 and we won't call it again we won't have that infinite loop so we can login again we can redirect and everything will work as it should so this was the login with access and refresh tokens also if you want a more complicated authentication course i will provide the link in the description of this video the ultimate authentication course with node.js as weld you can pick whatever backend that you want apart from node.js but in this course you will learn uh logging with using two-factor authentication with google authenticator and also social authentication with your google account if you are interested you can get this course on or you can get the node.js bundle for just eight dollars a month if you are not in europe if you are in europe is 9.52 so is up to you thank you for watching this course and don't forget to like share and subscribe thank you
Info
Channel: Scalable Scripts
Views: 11,261
Rating: undefined out of 5
Keywords: coding, programming, full stack development, scalable scripts, programming tutorials, developer, coder, software, laravel, react, vue, angular, django, python, nestjs, nextjs, nuxtjs, golang, denojs, nodejs, microservices, docker, kubernetes, rabbitmq, kafka, event driven architecture, event driven design, containers, mircorservices architecture, api, spa, single page application, c#, java, kotlin, .net core, java spring boot
Id: Y86k1Is45Uo
Channel Id: undefined
Length: 22min 16sec (1336 seconds)
Published: Thu Feb 10 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.