SvelteKit User Authentication With Auth.js | OAuth 2.0 Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on guys it's Cooper codes and in this video I'm going to show you how to integrate ar.js with spelt kit ar.js is a really amazing way to manage authentication for your website without using an external provider like superbase or clerk it's really simple to use and it supports any ooth service in this video I'm going to show off how to use GitHub with o. JS but you can really use any ooth provider you want the steps are going to be very similar so if we go in here and press sign in with GitHub it's going to bring us to the GitHub sign on page we can then press authorize Cooper codes we will then be redirected back to our website with a signed in user from GitHub a cool part of this tutorial is I'm going to show you how to grab the GitHub access token or the access token for whatever OA service you're using I'm then going to use the access token to get my followers list so I can press this button here and it's going to give me a list of all of my GitHub followers and then of course if we press the sign out button we are going to get signed out so let's do that right now let's get started by opening a blank folder in VSS code all right so now we're over in VSS code with a completely empty project I'm going to pull the terminal up here like this go over to terminal and now we can create our spelc project by saying npm create spelt at latest and then the name of our project which I'm just going to say log in- test I want to use the skeleton project here so you can use the arrow keys to go up and down select skeleton I'm going to use typescript with the typescript syntax so I'm going to press yes there and I don't need any of these extras so I'm just going to press enter all right so our project has been created in this login test here I'm going to enter this created project by saying CD login test like that and then I'm going to install two additional packages for the actual authentication logic I'm going to say npm install at o/c core which is the OJs core library and then also at o/ spelt kit which is the spelt kit specific specific stuff for this Library we can then press enter for this video we are going to make some environment variables so just in case you want to npm install d-d so as a Dev dependency EnV which allows us to use a EnV file for invironment variables so we can press enter to install that so before we write any felt logic we need to set up our environment variables so we can go up here and create a EnV file inside of here we are going to make environment variables specific to our ooth project this can include something like a client ID or a client secret but we don't have any of those variables yet so let's go over to GitHub and create our ooth client so I've gone over to github.com and I'm already logged in with my account so if you're not logged in go to the top right and this sign in eventually you can press your little profile icon here and you're going to want to go to settings inside of settings you're going to want to press the developer settings if you scroll down on the left here inside of developer settings you're going to have the option to create an oo app so right here we can press oo apps you'll see I already have some older applications in here but I'm going to press new aath app in the top right we can create an application name I'm just going to say login test app I know I'm creative for the homepage URL we are going to just use the Local Host URLs if you're deploying to a production environment the only change you'll have to make is to make sure to change these URLs to whatever your production UR L is and I'm going to cover that further in a second here when I finish this URL down here you can make an application description such as subscribe to Cooper codes or else your authentication project will break uh I actually heard that's true so you should probably do that okay I'm just messing with you guys there for the authorization callback URL this is a URL that our authorization is going to use in the background and it has to be a very specific path so it has to be HTTP SL SL localhost 5173 SLO SLC callback SL GitHub so this is the specific oth callback URL for GitHub specifically so each provider has its own URL and so if I were to use Facebook instead it would be slf Facebook if I already use Google it would be SLG gooogle you can look specifically at the O.J documentation for what this link is but for GitHub it's simple just SL GitHub I'm just going to enable device flow because um it seems like fun it technically what it does is it allows you to sign in through the command line I'm not doing that in this tutorial but you guys can try it out so if you guys wanted to deploy your ooth application to production for example you would change your homepage URL and your callback URL by doing this you're going to want to make sure it's https if you're using an https link and then whatever the name of your website is for example we can do google.com so if we were to do the authentication for Google it would be that and down here you would do the same thing where it would be your google.com and then you just do the exact same call back path like that but make sure to contrl Z and have your regular Local Host 5173 cuz this is what we're going to be interacting with locally so now we are all set to register our application here so hopefully you guys have this EnV file created in the background I'm going to start by getting our client ID here copying it going over here and saying GitHub ID is equal to that string then I'm going to go over to our client secrets and I'm going to press generate a new client secret this thing is only ever going to show Once if you accidentally don't get this or it goes away from you you can just make another one but it's only going to show Once to you and we can save this as gith hubor secret is equal to this string here and with OJs there's one more interesting environment variable we have to add which is oore secret this has to be a string of a random 32 characters so we're not going to get this from any external Source there's this cool website you can use called generat secret. veral doapp and it's going to give you a random 32 characters you see if I keep refreshing this I will continuously get random characters forever but we can use any of these copy it and bring it over to our application like this this o secret is something that o. JS uses in the background we're actually never going to work with it directly so if you're like why do we have to do that it's because o. JS is using it in the background and so before we get into the setup part here I'm going to quickly add Tailwind to this application there is this really cool Library called spelt ad and so we can say npx spelt dad at latest and then Tailwind CSS usually setting up Tailwind is a pain but if you run this command in your spelit application it's going to set up everything for you to the point where you can just instantly start using Tailwind classes this is just going to make our application look okay when we're working on it in this tutorial so you can press enter there then you're going to want to run another npm install for everything that they just added through tail and CSS there all right now we're good to go and we can do an npm runev to see our site running locally to make things look a little bit nicer I'm going to add some padding around the website so it's not directly on the corner here and then we're going to get into creating the .js client so we can access this route here just Local Host 5174 by going into our source folder going into our routes and going into the plus page dos felt I'm going to make a little div around our content here and it's just going to have a simple class is equal to p-4 this is going to give a padding of 24 around our text and so now our text won't be so in the corner but this isn't really a UI tutorial just to make things look a little bit better all right so now we can actually initialize off. JS in our project so if we go over to our source folder here at the very top so even outside of our routes folder we want want to make an O.S this is where the actual o client will live in our spelit application and the only thing it's going to happen in here is we are going to create the client so to create the client we want to import spelt kit o from oel kit and we also want to import the certain provider we're using so we can say import GitHub from at spelit providers SL GitHub and this is a default export so you can make a name whatever you want so I'm just going to do the correct capitalizations there I'm then going to import our GitHub ID and our GitHub secrets from our EnV variables so you can do import GitHub ID and then GitHub secret so to access this EnV file within spell kit you can always use this EnV static private and so this is actually getting the values of these EnV variables here so back to O.S we can then build our little spel kit o by saying spel kit o like this and it's going to take in a config object like this the config object is going to have a very important property called providers so this provids property here is going to be an array of all the different providers you want your application to use and so we can use the GitHub provider like this and this GitHub provider is actually an object that also has its own config object here and so what this provider object is pretty much looking for is all the different things it needs to set up the GitHub provider we first need to tell GitHub that the client ID is going to be GitHub ID and then the client secret is going to be GitHub secret that's all you need to do to enable GitHub in your application you could also do any other provider so let just say other provider and you can stack them just like this and that's not a real provider so it's going to give me an error but you can pretty much have a list of all the different providers you're allowing someone to use in your application but for us it's just GitHub so we're just going to have this and this spel kit o is going to export something very important so we can say const object is equal to spel Kit o this is syntax you'll see a lot in JavaScript what it pretty much means is this spel kit o is creating an object and we want some of the things that it is creating for example we want the handle from a spel kit o and so we need to export const handle and this handle is very important because it allows us to handle server requests so for example if GitHub talks back to our application it is handled by the handle here but we're not using it quite yet one thing we need to make is the Plus hooks. server. Ts you could imagine Plus hooks. server. Ts to be the way that other servers communicate with your spelit application it's kind of strange syntax but in order to use the Handler inside of our application we can just say export handle fromo this means that any server request that's incoming to our spelet application is going to be handled by the authentication here it definitely does kind of work in the background so if this syntax is confusing hopefully it makes more sense since we get to the end of the project here so now we can head over to our page. spelt and create some functionality to log in our user so in our page here I'm going to make a script at the top here going to make sure I set it's language equal to typescript and before we get designing some components I'm going to introduce a couple things to show you how the authentication works the first thing we can do is import some functions called sign in and sign out and these are being exported from at o/ spelit SL client this o spelit client is how we communicate with the spelit client so you could imagine if we do a sign in function call like this it's going to run the L logic to sign in user doing everything for us and then sign out is going to run the logic to sign out user and you'll see for the sign in we can even use a certain provider for example we're going to sign in with GitHub like this which as you guys could imagine is use the sign in with GitHub logic which is something that they've already developed for us so all we have to do is tell it to use the GitHub provider another important part here is to import the page from Dollar Sign app SL stores this is where all of our page data gets stored but importantly we can access the user's current authentication session by going to dollar sign page. dat. session and this is going to show us stuff like the user an image they have and other things like that and so to make what's in the session obvious especially for beginners is I'm going to console.log dollar sign page. dat do session like that and again guys this is your authentication session so if you're ever confused as to where is the user what's happening with them it's always going to be in this page data. session and so down here we are going to make a if statement that's pretty much going to say if the user is logged in show something if the user is not logged in show something else so I'm going to go in here and say pound sign if dollar sign page. dat. session so if that's an actual object that exists show something then I'm going to do an else statement here show something else and then I'm going to close off or if like this and so if the users log in I'm just going to show a simple header saying you are logged in and if they're not logged in I'm going to show a simple header saying you are not logged in so if we go over to our website right now we can see that we are currently not logged in and if we inspect element here our current page session is undefined there's nothing in there and so in the you are not logged in part of this we can make a button that the user can click to log in so I'm going to say sign in with GitHub I'm also going to make some styling here for the button so I'm going to say BG dl-500 py-1 so padding in the y direction of one and then px-2 so let's save this boom boom so there's our signin button I can make that look a little bit better let's go in here I'm going to say rounded text- white and then font Das Boldt all right it's not the best thing I've ever seen but let's and it's going to work so that's all we need right now if we press this button there's no functionality actually happening we can go in here and make an onclick and we can set it equal to an arrow function so this Arrow function is defining the logic of what we want to have happen here right we can then call this signin function from above and use a specific provider so for example GitHub and you can see my VSS code's autofilling all the different supported providers you got notion you got Pinterest you got Reddit you got everything in there there and so I'm just going to use GitHub like this and that's going to start the signin process for GitHub so the sign in with GitHub isn't going to work quite yet because we have to pass the current session to the page. dat. session and guys before we do that I'm realizing I made a mistake on the Plus hooks. server. Ts here it should just be hooks. server. TS like that and I made that mistake because I was thinking of this next thing we have to make which is plus layout. server .ts this layout is actually where we pass the current session into the page. dat. session so we can go over to layout. server. TS and the layout always has a very important load function so it's going to load server side any data we need and so you can import the serers side load type in typescript by saying import type layout server load from types like that and so we can export con con load is typed to layout server load is equal to an async function that has the current server events that we're going to pass into an arrow function here or sorry this entire thing is an arrow function is what I meant so inside of this asynchronous function what we're going to do is we're going to return an object which is going to be our page. dat so inside of this page. dat object we can say that the session is equal to await event. locals . off event. locals if you look here allows us to have data that was added to the request within the handle hook so handles adding some stuff to event. locals for us that might be kind of complicated for this tutorial but we can even see event. locals dots is going to show us everything that the handle Hook is giving us and remember that's the hook we added in hooks. server. TS and off is what allows us to get the user's current authentication session we can then press save here to save this and now we know that when our page loads we're going to get access to the user session so let's go over to page. spelts uh and I restarted my application because sometimes it can be weird with the layout. server. TS so be sure to do that so I'm going to press npm runev now our site is now showing or you are not logged in sign in with GitHub so we can now press sign in with GitHub it's going to redirect us to that oo link and it's doing all this in the background so even if you choose a different provider is going to send you to this link here I'm then going to press authorize Cooper codes and it's going to send me back to the UR are logged in and you'll see our page. dat. session has an object which shows when the token expires and it also shows who our current user is and so we can actually show this data to our website here so let's make some functionality that's going to show this to our user and even in our console here we can see what the session currently is so I'm going to do an if statement that says if the user has an image because not every single OA service is going to provide an image like this so if dollar sign page. dat. session. user. image and user might not exist so I have to do a question mark here to make that happy this question mark If You' never seen it before pretty means if the user exists then grab the do image property it's not doing like an if statement or anything like that but it's like that's kind of the logic behind it and so I'm just going to make a simple image here here I'm going to give it a class of width D12 and height D12 cuz it's going to be my profile image so just going to be a square it's going to have an ALT of equal to user profile that's just for anyone with like a screen reader or anything like that and then the source of the image is going to be equal to this right here boom so if we go back to our site we can see we have our little login image and it's technically a square but I have a white background from an image so doesn't look great here and I can also do something like this where I can say well paragraph signed in as and then the dollar sign page. dat. session. user and then instead of getting the image we're going to do question mark. name so it's going to grab the username which is going to show us signed in his Cooper codes let's go that's who I am and finally let's make a little sign out button and I'm just going to copy the button we had from before to make our lives easier with all that styling on it and I'm going to change the text of the button to be sign out and instead of calling the signin function I'm just going to call the sign out function which again is something provided to us from o/ spelit client kind of an interesting side note but if we ever have some logic where a user doesn't press a button but you want to force them to sign out or force them to sign in right you can just run these functions wherever you want you don't only have to run them when the user clicks a button but if we go back to our application here and then we refresh we can then press the sign out button and it's going to sign us out and our session gets cleared you guys will see that GitHub is actually doing some caching for us and so if we try to sign in again it's not going to put us through the GitHub process at all and it's instead just going to give us the same session and we are just a signed in user like usual and so this is kind of the full authentication part of the video I'm now going to show you guys how to access the users's access token access tokens are important for if you want to get a certain GitHub service or get a certain Google service with a certain users's access token this is the way you can do it with off. JS so we can go on over here and we're actually going to edit our O.S here so our o client and so the O client gives us access to something important called callbacks these are functions that get called when things happen for example does a Json web token get sent to server or does a Json web token change which means you want to change the session with whatever is in there these are things that you can do with the callback functions so I can say async JWT and so this JWT function is called whenever the Json web token gets created or updated o. JS only uses portions of these tokens which is why you have to do unique Logic for it so for example this Json web token has some parameters for example like the new token or the user account which is only available when someone signs in or signs up this account is going to act this account variable here is what has the access token and so if an account exists and it's not just some other type of token change then the token. access token is going to be equal to account. access token like this and then we are going to return our token this is kind of some strange logic but whenever our Json web token changes it's then going to trigger a change to our session kind of like what I talked about here but it was pretty brief it has a similar async session call back right right here and inside of here you get access to the session token and the user inside of here we can say session. access. accessor token is equal to token. access token just like we defined above it's literally going like top down through these routes even though they're in different functions also we're technically changing things to these sessions typescript so I know I'm going to get a flame for this I'm going to use an at ts- ignore just to make the tutorial more simple I'm not going to mess with the session types but if you look up off. JS change session types you'll find some stuff on it and I'm going to finally return the session so now we actually have to go back and relog in the user because this access token only gets updated when someone signs in or when they sign up so let's go back to our site and we can then press sign out we're going to have an empty session then we can sign in again and boom when we sign in the user's access token gets applied to our current session session so even on the web client here we have access to the access token this is great if you want to do any client side requests for example we can make a button to get a user's followers so hopefully you guys have at least one follower on GitHub to do this but uh it will even send you an empty array if you got no followers so let's go back to our code here and we can go over to our page. spelts and I'm going to copy the logic for the button again and I'm going to make it a bit of a different blue color actually let's make it darker so so blue 800 here and it's going to say get followers list and we can instead call a function instead of this so I'm just going to say get follower list for a certain user before we make the get follower list let's go check this button actually looks good all right so we got our two buttons here I think that's fine for now and so we can scroll up and make an async function get follower list just like this and so now this function call right here is going to call right here and so just to reference what I'm using is I'm using this GitHub documentation here where we can do a simple get request to/ users slf followers with a search and access token to then give us the users followers I'm going to convert this code here into JavaScript code pretty much so we can go over to JavaScript and we can do that fetch request to the GitHub API by saying await Fetch and then the link is going to be https api. github.com user slf followers then inside of here we can pass in some options for example the headers it's very specific about you have to have an accept header of this weird GitHub format which is application SLV and. GitHub plus Json and then you're going to have an authorization header which is going to be Bearer which is a common Syntax for if you use a user's token it's going to be Bearer a space and then the token we can get the token from dollar sign page. dat. session. accessor token this is not going to like us because of typescript so again I'm going to do an at ts. ignore but that's the last one because again it's using that session and it doesn't like it when we change the session types a weird one here is we're going to have to do an x- GitHub API dvion um I could talk about what API versions are but pretty much it's telling us that there's a certain snapshot in time so this one is 20 22 11 sl28 this is a snapshot in time when GitHub says we're going to support this version of the API for a long time even if we release new ones and so you'll see API versions happen in that context especially for really big apis this is the specific version you have to use to get access to this request here and because we're passing in this access token right here it knows who the user is so we don't have to say any weird like username or anything like that so when this request is done we're going to say dot then grab the data of the request and then we're going to transform it into a data. Json so I'm going to say return data. Json it's going to put the data into a Json format then I'm going to say dot then the data is kind of continuing through the pipeline is a way to think of this and then I'm going to console.log data like this data is actually going to be an array where it's user one user 2 user 3 Etc and so we can actually save this array inside of a simple variable in spel kit so I'm going to scroll above and just say let vol follower list be equal to an empty array for the time being and this new data is then going to replace it so I'm going to say follower list is equal to data and I'm just going to console.log follower list as well oh and I'm actually going to make this follower list be an any type I know guys my this isn't really a typescript tutorial but I don't want to spend time typing it exactly to how GitHub has it here but now we should be able to press this get follower list and we're not going to see anything yet but in the console it's going to show us this array of users so let's go back to our site here and we can see we have an empty array at least and so I'm going to press get follower list oh and it's going to give us a list of 30 objects which are all of my GitHub followers or at least the first 30 and so you can see this login property has the user's name and so that's what I'm going to show throughout the list here is I'm going to show each username like that so we can go down here and a very simple each statement inside of spelts I'm just going to make a simple unordered list and I'm going to limit its width so I'm going to say class is equal to width -64 then I'm going to say for each follower list as item comma Index this allows us to go over each object in the follower list so I'm going to say slash each at the end and I'm just going to make a simple list item like this where it's going to show the item. login because that's what we saw is the user's kind of simple name it's going to yell for the IDS here because it wants every single item to have a unique ID so I'm going to say ID is equal to follower plus index and I'm going to limit the width here too to say class is equal to width -64 so when the follower list gets loaded it's going to load in each thing as a list item like this and so I just refreshed my page over here so we can then do a get follower list and boom it's going to give me a bunch of followers from my GitHub and this might not seem like much but whatever aat service you decide to use use you have access to that access token so whatever API request you have to do anything along those lines can be handled even within .js and it took us a while to get there but we're building out some pretty decent functionality even if it doesn't look the prettiest all right guys hopefully this was a really helpful introduction into .js and using it with a spell kit I think for early on projects using something like OJs to be a really quick solution can be helpful before you move on to something like superbase for authentication or clerk like authentic ification so I mainly made this video to give you guys a bunch of different options I am a YouTuber and I am Shameless so if you made it this far feel free to check out my website theod letter.com I've been working on this a bunch recently even with my own writer and it's been going great we've been having a lot of really amazing articles being written and it's super time efficient I'm not here to waste your time with my newsletter so it's kind of a really cool service where you get to know all the latest events in Tech and yeah I'd suggest you go subscribe otherwise guys thank you so much for watching
Info
Channel: Cooper Codes
Views: 2,563
Rating: undefined out of 5
Keywords:
Id: ehmc1Zgu_EU
Channel Id: undefined
Length: 29min 27sec (1767 seconds)
Published: Mon Mar 11 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.