Add Authentication in Next.js with Auth0

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
next js is one of the most exciting frameworks out there with it you can build powerful full stack applications using react but the thing you might be missing is how do you add authentication in next.js well in this video we're going to take a to-do app which uses airtable as a database and we're going to add authentication on top of it using auth0 inside of next.js so let's go ahead and dive in if you're new to the all zero channel my name is james quick and i am part of the developer advocate team here at off zero now we have a lot of exciting content coming up in youtube that we are planning or we'll be working on so if you have ideas on things you would like to see make sure to comment below send us requests also if you enjoy the video make sure to like subscribe to the channel and then turn on the notification bell so that you can get updates as we come up with more content all of that said let's go ahead and dive in all right so a couple of resources for us to look at as we get started one we're going to be using this next js off zero package for incorporating authentication into our next js app so i'll put a link to this repository in the description below you can go and check this out as well there's good documentation on the getting started section of this readme as well so this is kind of what we're going to go through here in a second now there also is a blog post on the all zero blog which is the ultimate guide to nexjs authentication which covers a couple of different ways you can do authentication with all zero including the route that we'll look at now so you can go and read more about auth and nexjs in this article and then lastly i want to give you the link to the actual source code that we're going to work with today so there's this authenticated to do app with next.js airtable and auth0 it uses some cool technologies to create an authenticated to-do app and i think it will be a lot of fun and if we look in here there's two branches so what what we're gonna do is we're gonna start with the add off zero start branch that rips out all the authentication stuff and we're just gonna add it back in so actually i've got the code checked out and i'm in this add off zero start branch and i'm gonna go ahead and start this application and we'll take a look at what we already have running and then we'll fill in the gaps of adding authentication on top of that all right so it looks like this thing is ready let's head on over to localhost 3000 let's refresh this just just to show you what's going on and we see a basic to-do app i need to do my laundry at some point today i actually just reloaded now but need to do my laundry so i can click uh this actually sends a request to the server and updates this information inside of airtable so airtable if you've never used it before is a really quick and easy way to kind of set up like an excel sheet type database which is really really awesome and really cool for demos like this so you can see all the information that i've got in here including which one did we just update the do my laundry one just got updated and you can see that it's checked here i could also come in and uncheck that and then if i refresh just to show you this is working now do my laundry is unchecked so all this information is connected to airtable you don't have to know all the details about that but if you would like to learn how to build this entire application in a series let me know in the comments below i think we'll we will probably break this whole thing out into a few different videos and create a series where you can see how we do all of this stuff together but in the meantime this is what we're starting with and now we just want to add authentication on top of it so if we come to the documentation for the next js austier library if we scroll down there's a couple of things we need to do first off inside of all zero we need to create what's considered a regular web application and then we need to give it a couple of urls now the way authentication works in this case in this case is through redirect so what will happen is nextgs will send the user off to auth0 off zero will handle the login process and then redirect the user back to our application and in that because of that we will want to send the user back to a specific url which in this case is going to be our callback url and then our allowed logout urls is basically just saying like where are we allowing people to log out from in this case localhost 3000 because we're running this locally so let's get into step one let's go in uh into the osceola dashboard this is mine here and i've got several applications created but i'm going to create a new one here so this will be my authenticated to do next js app and then we want to choose the regular web application here so we'll go ahead and create that and after that gets created you'll see there's a lot of different technologies to do our quick starts with so you can go through if you're if you're using another framework you can choose that we already kind of know what we're doing with next year so now i want to come down and eventually we'll grab this domain client id and client secret but we'll start with filling in those pieces of information the allowed callback url and the allowed logout url so i can come back to the documentation here and i'll grab here's the callback url which goes to slash callback and i'll paste that in and then we also have the just localhost 3000 as the allowed logout url down here all right and i want to make sure that we scroll down to the very bottom here to go ahead and click save changes to make sure those things take effect so that's all we really need to do in here other than we want to copy our domain client id and our secret we'll come back to that in a second so the next step in here is to create this off0 configuration file and the cool thing is even though this looks kind of intimidating one most of these properties in here are just kind of default so we don't actually need to specify them but the other aspect of this is that we can just copy and paste this into our project so i'm going to come into my utils directory and i've got a little helper in here for working with airtable and i'm going to create an auth0 file auth0js and then just paste in that little snippet that i copied from the documentation now all of this stuff is just a configuration for all zero so we pass in this configuration object that has all these different properties and again we don't really need to know all of these things we don't really have to specify all these things a lot of them are defaults if you look optional optional optional and so on really the the couple of things we care about are the domain the client id the secret the scopes here is just kind of asking what are what are we wanting to get about the user in this case we want to get the open id and the profile for the user so we'll get information about the user and then the redirect uri is after the user is redirected to all zero the authentication takes place where are they coming back to that's the callback that we will define in a second and then after they log out where will they be redirected to as well so i'm going to take a second and i'm going to copy the domain and client id in here and then we'll talk about what to do with the secret in a second and i've got my domain and my client id copied in here these are not private credentials it's okay for these to be checked into your code but it would be a little bit better if we actually used environment variables for this so inside of the repo there's an env.sample file so if you wanted to get this running you would need to create an api key and air table and create a base and a table inside of air table so you need to fill that out as well as then we've got the all zero domain secret and client id that's how we're actually gonna work with this so what i'm gonna do is i'm gonna take a second pause the video i'm gonna fill in these variables in the dot emv.local that's the file you'll need to have to run this and i'm going to fill in my credentials and have those ready and then we'll come back in a second all right i got my environment variables filled in in the env.localfile.env.local file and one thing i didn't mention is the cookie secret here this is just kind of a random string for now just kind of type something in there and that will be good enough so for now just type in a long string 32 characters or so just a random one for the cookie secret and that will be good enough for now and then now instead of inside of our osceola configuration instead of hard coding these values i'm going to reference them from our environment variable so process.env and then the name of the actual values so i'll go ahead and type those in all right so we've got those variables now coming from our environment variables and next.js is able to pick those up automatically from that.env.local file and here we're not importing a config file so we're doing that from environment variable so now this configuration file for auth0 is ready to go so let's scroll back over to the documentation and after you have that in place now we can start to define these api routes so next.js is really cool where you can define just a file inside of your api directory and it will basically host that as a serverless function so for this i'm going to create inside of api i'm going to create a new file and call it login js and then just paste in the snippet now all this does is it defines a serverless function called login and it calls the austiropackage.handle login and the only thing will change in here is this directory the all0 file is inside of the utils directory that's inside of api already so this should just be a going directly to that utils directory like so all right so there is our login route and then if we scroll down we'll do kind of the same thing here for our callback so we'll copy this little snippet and this is going to be inside of api we'll call this our callback js and we'll paste in this snippet as well and we'll fix this reference to utils should just be dot slash there as well so there's our login and our callback and then we can also scroll down to handler handle not hander our logout as well so inside of api we'll add one more file and this will be logout.js and we'll go ahead and paste that snippet in there so now we have all the api routes that we need now we can start to actually work with our login process and our user so let's come back over to the index js page and if we scroll down and everything's all the code is really kind of inside of this page i haven't really broken it out a whole lot but if we scroll down we have this function here for git server side props and get server side props is basically our way to do server server side generated pages where in this case what we want to do is grab the logged in user and then we want to query only records that are associated with that user we'll come back to that in a second and the other thing i want to show you is inside of this nav bar there is a login button and a log out button and this is based on whether or not the user is being passed into this component this home component so what we want to do is scroll back down and we will say that the user coming in here to start is going to be null oh the one last thing we're missing is we didn't actually install the package so we want to make sure that we install this package first and this is the first step that we just skipped over here so we'll make sure that we install the actual all zero next js package once that's installed we'll start this up again with npm run dev and then we'll be able to test out the login process so let's run this again npm run dev all right now we should be able to kick off this login process and this will redirect us over to all zero in this case i think it's gonna already pick up it's already logging me in with my twitter account i've got some social connections already connected to this tenant that's okay you might not have that if you don't you will see a gmail option and a register option with email and password and you can do either one of those things so nothing really changed here and the problem is we're actually logged in technically but we're not passing the user into this home page file so it doesn't know that the user is there so what we want to do is grab this user and because of the login api routes and the library that we're using almost all of this is taken care of for us so we can say cot session and we're going to grab our off0 library we'll import that in a second or all zero config file and we'll call git session and we'll pass in the context dot request so the request that comes on this context object will pass it into the off zero get session call and then if we scroll up we'll just need to import this thing at the top so we will import auth 0 from api utils auth 0. all right so now that we have that thing we're able to grab the session and then on that session is an actual user object so we can grab the user from that session and so what we'll do is we will use some nice javascript here to say either we will pass in the actual user from the session if there is one or we'll pass in null and the last thing i want to make sure that we do is await that get get session that's an asynchronous call so we want to make sure we await and get the actual data that comes back and now that that is ready to go i can come over and now you see that we the user is logged in you see the logout button but you still see all of the different items regardless of whether or not they're associated with user we'll come back to this in a second so let's just kind of show really quickly as we go through this log out process uh this will get us logged out now it says log in to save to dues and we can log back in and kind of see this process at work now here's earlier it kind of logged me in automatically with twitter now i'm getting to choose i can log in in my case i've got twitter configured you will have google configured so you can go this this route as well and then i get back here so the login process is working what we want to do though is update the to do so we only get to do's for the logged in user and the way we do that in air table is i will pass inside of our select we'll pass an object with a filter by formula and that formula will be i'm going to use the es6 template literal string here we'll say we want to get records where the user id is matching the session.user.sub now the the sub property is basically the unique identifier for the user and we're actually going to do this a little bit differently so we're going to say let to do's and just kind of initialize that as an empty array and then we'll say if the session dot user so if there is a user attached with that session then we'll update our to-do's to be the ones that we query by the user now the reason we do this is we don't want to display any to-do's in the home page if it's not associated with a specific user we don't want them to be able to see other people's information so we initialized to do to an empty array if there is a user we will grab the to do's based on that user's id which in this case comes from the user.sub and then we still pass it in here just like this so let's go back and uh refresh this application now and now we see there's only these three things here and if we look inside of air table you can see these are the ones associated with that google account and if i toggle one of these to be uncompleted and refresh you'll see that should be reflected in here now the last thing i want to show you is how to protect your api route so that in the in the get to do's for example you only allow the user to get to dues if they're actually logged in and then they only get the to-do's that are associated with themselves so what we're gonna do is from auth0 so we're going to import our off xero again from utils off 0. all right so we'll import that thing and then instead of just exporting a default function we're going to wrap this with all zero dot require authentication and i'm going to wrap this entire thing now what this will do is it will check to make sure that the user is logged in before it even lets this callback happen which is really really powerful and then if the user is logged in we can get that user from it's actually going to look a little different we're going to have to destructure user from a weight off zero dot get session by passing in the incoming request now this looks a lot very familiar to what we just did in that index route there so uh now if i were to call the get to dues this api endpoint it would make sure that the user is authenticated let's also check this in the create to do so let's do the same thing in a create to do and then we'll be able to show this off here in a second so we'll import auth0 from utils off 0 again and then we'll wrap this entire thing again with all zero dot require authentication and again this is the beauty of the library where it's going to take care of all of the checking to see if the user is logged in and handle it appropriately if not and from here let's just save this well actually we could go ahead and grab the user so we'll grab the user from the auth0.get session and we'll pass in that request again so to be able to test this or show you that this is working what we'll do is we'll log out of the application and then we'll kind of fake that we're logged in even though we're not so let's just pass in an empty object this is just for testing so you can see that this is working and uh now if we refresh it should think that we're logged in although we're really not and what should happen is in a network tab if we look when we try to add one of these items let's look at network tab and xhr we submit this and it should come back as a 401. now we didn't i've got some logic in here to be able to handle that situation but the most important thing is if someone try to make a request directly to that api endpoint you can now see that it's protected and it returns back a 401 to say that that user is not authorized now if we come back and fix our application and let the real user take over here or be a part of this and we will refresh in here and we should have to go through the login process again this is the fun part about testing authenticated applications is this time i'll log in with twitter just because so we'll go ahead and set that up and then i should see my specific items in here and i can add another one and hopefully this one will go through so that actually was allowed to go through because the user is logged in but the cool thing is this little wrapper here on the create to do by wrapping this entire function will not only check that the user is logged in but then also give us the uh visibility to the user getting the user from the session now we could go through and do this for all of the other endpoints there's also another layer of this authentication that would double check to make sure if a user is updating one or deleting one that not only is the user logged in but the user is already the owner of that item as well so i think that's going to be part of maybe a longer term um kind of mini course here i want to know in the comments please let me know if you would be interested in seeing how to build out this entire thing with next.js airtable and auth0 as well as tailwind css if you want to see how to do all of that in a little mini series let me know in the comments below and in the meantime if you enjoyed the video make sure to give it a like and subscribe to the channel you can also check us out on the austral channel on twitch if you ever want to interact with us and ask us questions real time it's a lot of fun go ahead and check us out on twitch at twitch.tv all zero we'd love to see you there thanks again for checking out the video and we'll see you in the next one
Info
Channel: Auth0
Views: 10,893
Rating: undefined out of 5
Keywords: react authenticat, react login, authentication auth0, nextjs authentication, nextjs auth0, nextjs tutorial, json web tokens, react security, how to add login react, how to add login nextjs, nextjs, react auth0, react authentication and authorization, react login component, react authentication login, web development, jamstack, serverless functions, serverless authentication, cookies, oauth2, openid connect, identity, auth0 api authentication, auth0 node js authentication
Id: 4sXAWsUub-s
Channel Id: undefined
Length: 19min 36sec (1176 seconds)
Published: Wed Sep 09 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.