Next.js 13 Role Based Authorization with Middleware & NextAuth

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in today's video we will learn how to add role-based authorization to our Nexus 13 application so let's get right into it let's get started by opening up this repository in GitHub and cloning it so I'm going to click over here and copy the URL and switch to the terminal and paste in git clone and then the Repository like that then I'm going to open up that repo in vs code like this and let's actually quickly check out the GitHub repo one more time so if we look at the princess we have over here we have the starting point Brands and how this repo works is that next we want to check out that starting point print and start working from there because what I already did was to set up next auth and all the authentication logic in that starting point Brands and that's just to speed things up so we don't have to use time on this video on setting up the next alt in the next JS project and if you want to learn how to set up the next odd for an access 13 project I have a video about that so please do check out that on the channel but now let's check out this uh one starting point brands in our vs code so I'll open up terminal and type in git checkout and then the one starting point Brands like this looks like we are on it that's great so next I will run yarn install like this and then let's just fire up the application and see how it works the dev server is running and I'll open up the localhost 3000 and looks like we have a login button or sign in button and a text not signed in so let's click the sign in and sign in with GitHub okay so one thing we forgot to do was to add environment variables to our application so I'll switch back to the vs code and let's create a new file to the root of the directory called dot in dot local like this and inside of this file we want to Define four environment variables first is the GitHub secret then GitHub ID next odd secret and next auth URL and these are all required for us in order to authenticate with GitHub so let's add the GitHub secret and GitHub ID and how we can do that is to go to the GitHub and open up developer settings page so you can go to this URL and select the all out apps and we can create new or out app and let's give our application a name like this then the homepage URL which is localhost in our case then we don't have to add any description and for the authorization callback URL we will use this one over here now let's click register and just like that our application is created and we get the client ID and this is the value we want to copy and paste in for the GitHub ID environment variable the next we want to generate a new client secret let's click that and it will generate a secret for us which is this one over here so I'll copy that go to the vs code and paste it in for the GitHub Secret okay so now we have all the GitHub stuff in here for the next odd secret we can just add some secret for now so I will just add test and the next auth URL we can add localhost like this let's save it and now I think our application should work so let's run the dev server okay and switch to the browser and let's go to the localhost 3000. okay let me make this a bit bigger so let's click the sign in button sign in with GitHub okay looks like there is something wrong looks like it redirects us to the localhost so I think we need to modify the next auth URL to be localhost 3000 like this so let's save that switch back to the browser and I'll go to the localhost 3000 again and let's click sign in sign in with GitHub now it asks if we authorize The All Out app let's authorize and look like we are signed in so we get the user information displayed for us over here and one thing I want to mention about this authentication is that right now the route handlers are new thing for Nexus 13 but next odd doesn't work with them yet so that is why we have still the pages folder inside of here and we have init the API route auth and the next auth JS file which handles the authentication so just a heads up for that so in the future I'm sure we will have this auth API route inside of this app folder and inside of the route handlers or something similar but at the moment the next odd is not supported in the app folder so that's why we are using it in the pages and API route folder but next what we actually want to do is add couple of more pages to this application so we can test the authorization between those pages so let's start by going to the app folder and I'll create a new folder called admin dashboard and inside of it I'll create the page or actually I just copy this page file from here and modify it like this so we are just printing a text this is admin dashboard then I'll create a new folder inside of the app folder called profile page and again I'll just copy this page file inside of it and modify it like this and it's just this place this is the profile page text so let's see if we go to the browser and the localhost slash admin dashboard like this we get the text and then if we test the profile page we get the correct text over there great but in order to make things a bit easier for us let's add links to those pages to our actually our layout file so I'll switch to the vs code and open up the layout file and over here I will add those links so just give me a second like this so what I did was important that the link from next link and edit links for the front page to the admin dashboard and the profile page so let's see the browser so we get those links up here so if we go admin dashboard profile page front page and looks like every link is working which is great and again I just want to say that I wanted to keep this application really simple and just focus on the authorization parts so it's easier to understand what is related to the authorization and what is not so that's why this application is pretty simple as you can see but hopefully you will learn better through this example so now when we go between these Pages we can see that we can access all of them because we are signed in but if we sign out and go to the pages well we can see that we can still access them so the first step let's add a check for all of these pages that they are only displayed when we are signed in and if we are not signed in we will be prompted to sign in and how we can do that is actually with next test middleware so I will add a middleware.js file to the same level as the app directory is so middleware.js and now let's open the next auth documentation regarding this middleware right here so how we can protect our whole application so every page will require authentication well all we have to do is add this one line to our middleware so let's copy that and paste it in to the middleware save it and let's switch to the browser and let's try to access the admin dashboard and looks like we are prompted with designing so we can't access the admin dashboard because we are not signed in so let's try the profile page same thing so let's actually sign in and see what happens so now we are on the profile page now we can access the admin page and the front page but as you might have seen if you sign out and go to the front page like this it will also prompt us for the sign in and this is actually something we don't want so let's modify the middleware so that only the admin dashboard and the profile page require us to sign in so I'll switch back to the vs code and let me add one line of code over here and I'll explain it after that okay so what I did was I exported this config variable from this middleware and inside of that I can define a matter which is an array of routes that we want to match this middleware for so right now this middleware should be only run for the admin dashboard route and the profile page route so let's see I'll switch the browser I'll go to the localhost 3000 and looks like we get the front page rendered and now if we click the admin dashboard we are prompted with sign in so looks like it's working so let's sign in and now we can access the profile page admin page and the front page okay so now our admin dashboard and profile page is protected with the sign in so we need to sign in in order to access them but let's say we wanted to only access or Grant access for this admin dashboard for users that have the role admin so let's see how we can do that next but before we get into that let me ask you a quick question what do the best programmers and Engineers have in common well they have a deep understanding of the key Concepts behind their work and the best place to learn them is brilliant.org with brilliant.org you can learn computer science and many other topics interactively in bite-sized chunks brilliant has thousands of lessons from foundational to Advanced Nat AI computer science data science and more plus they are adding more lessons every month I just recently had to brush up my algorithms and data structure skills and I found the perfect course for that from brilliant their Visual and Hands-On approach is such an effective and engaging way to learn that it makes the whole process of learning super fun and easy to try out everything that brilliant has to offer free for full 30 days visit brilliant.org or click the link in the description the first 200 of you will get 20 off brilliant's annual premium subscription so first we need to modify our middleware file and let's do it so that I'll add the code over here and let's go through it together after that okay so here's what the middleware looks like now so in order for us to add some authorization for the application we need to use this with auth from the next odd middleware and we will export it by default and inside of that we will Define a middleware function and then also some callbacks functions so let's start with the callbacks actually we are defining a authorized function and if this function returns true it will pass the authorization and if it returns false the authorization will fail so in this case we are getting the JWT token from the parameters and then just checking that it exists so if it exists we know that the user is authenticated and if not then we will return false and prompt the user with design in so that will be run first and if that returns true then this middleware function will be run and inside of this we are checking that if the path name is the admin dashboard so we can access the path name from the arrayquest and next URL so if the path name is the admin dashboard and the role is something else than admin then we are just returning a new response saying that hey you're not authorized and we are not going to the actual admin dashboard page so in this case we are accessing the role from the token which can be accessed in the next auth variable of the request and right now when we are using GitHub we are actually not getting a role property in the token so this should fail right now so let's test it out so if I save this and switch to the browser and try to access the admin dashboard Let me refresh the page we are getting the you are not authorized and that's just because GitHub doesn't return a role parameter so if we want to modify the token in the application we can do that so let's open the next auth JS file and inside of here we can for the auth options Define callbacks and if we want to add a role for the token just to test this out so that it works we can do the following like this so we are defining a callback called JWT and we can access the token from the parameters and right here we are just setting the role for the token and then returning that token so when we do it like this the token inside of the request over here will have the role that we defined in the next odd callbacks in this JWT callback so let's test this out I will save this switch to the browser and let's refresh the page and actually I think we need to re-log so let me sign out sign in sign in with GitHub okay we are signed in and now if we access the admin dashboard we can see the text over there so now we are authorized for it and now if we go back and let's say that our role would be member save it I will sign out sign in and try to access the admin dashboard we can see that it gives the not authorized message hopefully this didn't feel too complicated and you got at least some idea on how the authorization and role-based authorization Works inside of the next s13 and next alt I said I hope you got something out of this video and if you did please do leave a like And subscribe to the channel if you are not already
Info
Channel: Tuomo Kankaanpää
Views: 19,988
Rating: undefined out of 5
Keywords: next js, next js tutorial, next js 13, next js vs react, next js typescript, react, nextjs, nextjs 13, next js уроки, server side rendering, next js 13 tutorial, next 13, next.js tutorial, javascript, next.js 13, auth, authorization, auth jwt, authentication, nextauth, next auth, jack herrington, web dev cody, tuomo kankaanpaa, tuomo kankaanpää, sakura dev, firebase, oauth, auth0
Id: 9bI3ihPg5j0
Channel Id: undefined
Length: 17min 3sec (1023 seconds)
Published: Tue Mar 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.