Role Based Authorization with Next-Auth and Next.js 13

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi in this video I'm going to implement the user role-based authorization with next auth package in next.js version 13. and also at the end of this video I'm going to give you a practical example of how we can store the backend access tokens inside the next of sessions and how to include them in the requests that are being sent to the backend apis so without further Ado let's get into it this is the final form of application that we are going to work on today as you can see there are three pages in this application home page which everyone can see it whether you are logged in or not admin panel which only admin users can access this page and also a user panel which only no more users can access this so if I go ahead and click on the user panel I'm headed to the login page because I'm not logged in so if I log in with the user 1 which is a normal user and you can see that normal user now logged in and if I click on the user panel you can see that this time I can access to the user panel and here in this page there is also a get user profile button which fetches the user profile data from the backend API so if I click on this you can see that the username of the user is user run its name is mobile user and its role is user okay now if I want to go to the admin panel I'm again headed to the login page with this custom message which says that you're not authorized so this time I'm going to log in with the admin user you can see here the admin user is now logged in and if I click on the admin panel again now I can access to the admin panel page if I click on the get user profile here you can see the role of this user is admin so in this way when a user wants to do a specific action in our application we can authorize them based on each role whether it's admin or a normal user and yeah I think it's enough with the introduction and let's implement this with nexjs version 13 and next Earth package okay I open up my previous videos project which is about the next auth configuration and how to authenticate a user with username and password within the next JS version 13 with the help of next auth so if I go to the pages folder and API off and then open up the next auth configuration file you can see that in the authorized method here we've extract the username password from the credential here and then send a post request to our backend API which is on slash login and then pass the username and password to the body of our post request and the back can take care of authentication of the user with this username password and if the user is existed and the password is correct then it returns a user object along with a JWT access token which we can use it later in our request to the backend so if the user is not existed or the password is incorrect the backend side doesn't send us a user object so we just return no which means that the username and password is incred and the user is not authenticated and if you're not familiar with the next off package and how it works I highly recommend you to watch my previous video which is above the configurations and how to authenticate a user with username password so in this video we're not going to cover the basics of the next art we'll just cover the how to authorize a user based on its role which is whether it's admin or not so before we start let me show you when we send the post request to this backend API how it responds to us so I open up the insomnia which is just like the postman and here if I send a post request to this locals 8000 slash off slash login with this body username admin and password one two three if I send this you can see the back end sends us a user object along with the access toolkit the user object contains the username its phone name and also its role which is very important for us in this video now if I log in with another user user one for example and send the request you can see the user 1 and normal user and its role is user now not the admin So based on this rule we can authorize our users with specific action that they want to do and if our user has a role property and also an access token we have to kind of modify the user type inside the index auth in a way that it contains a role and access token for us so I go back to the vs code and the first thing you want to do to do this is to create a folder named types and inside this typist folder I'm going to create a file name interfaces .ts and here I'm going to Define an interface for our user object so user has a name as a role a username and also a access token the name of the user must be string or not or undefined this is very important if you don't Define the type of name of the user like this you can get an error later in this video so I've saved this and here in the typist folder I'm going to create another file called Next Dash off.d.ts the name of this file must be exact the same and it must be inside the typist folder and in this file we're going to define the shape of our session object so the first thing you want to do is to declare a module called next off and we put the next of inside the quotation marks then in this module we'll Define an interface called session and the session object must have a user object which is the type of our user which comes from the interfaces file not the user that comes from the next auth so in this way we override the shape of our session object in a way that now it has a user object with the type of our user interface we have just defined in the interfaces file so let's save this and go to the next of configuration file inside the pages folder and in this file after the providers list we're going to Define an object called callbacks and in this object we're going to Define two functions JWT function and session function so I'm going to say async because this is an async function JWT and then from the parameter of this JWT function we're going to distract the token and also the user and then return an object that contains the properties of both token and also the user so I'm going to spread the token here and also spread the user so in this way we're gonna merge the user object and token object into one object and then return it to the Token so the second function that I'm going to Define here is the session so I'm going to say async session and from the parameter of this session we're going to destructure the session token and also the user and then we set the session dot user to the Token object that we returned here from the JWT function so the type of this user here inside this session is the user interface that we have defined in the interfaces file so after that we're going to return this session and that's it so after calling the use session function we retrieve an object a session object that contains a user that have these properties so yeah I think it's done with the next art configuration file and now let's go for the middleware function so I open up the middlewealth.ts file here and this file has two lines of code that we have added in the previous video your first slide checks if the user is logged in if the user is not logged in it redirects the user to the login page and the second line tells that run the middleware for these routes in our application so this middleware is run for every route that starts with the admin or user in an application so these two lines of code do the authentication for us but not the authorization so to include the authorization we have to remove this line of code and then export a function which called without and that function is come from the next auth package so I'm going to say export default with off and then import it from the next auth slash middleware this function takes two parameters the first one is the middleware and the second one is the configuration object so we're going to Define our middleware inside it so I'm going to say function middleware and this middleware takes a wreck which stands for request and then after that function we have an object that contains the callbacks and this callback contains a authorized function and from the parameter of this authorized function we're gonna destructure the token and then this authorized function returns a Boolean if the Boolean is true the middleware allows the user to go ahead to do what he wants to do but if the return value of this authorized function is false the middleware redirects the user to the login page so here we're going to say that if the token exists then the user is authenticated and then it doesn't need to redirect the user to the login page so here we've transformed the token object to the Boolean if the token exists we return true and if the token is undefined return files from the authorize function so again if the authorized function returns files the middleware function redirects the user to the login page that we have specified in the next auth configuration file but if the the authorized function returns true the middleware function allows user to go ahead and do whatever he wants to do so this authorized function is kind of the authentication check for if the user is logged in or not so what about the authorization we implement the authorization inside the middleware function which we're going to Define here so here we say that if the wreck dot next URL got pathname that starts with slash admin and Rick dot next off the token that rule isn't equal to admin then return next response which comes from the next slash server that we write a new URL which contains the slash off slash login and then set a message parameters for it I'm going to say message equals to u r and not authorized and then break that URL essentially we say that if the route start with the admin and the role of the user is not admin then redirect the user to this slash off slash login and set a message parameter that says you are not authorized and that's it so here we can set another option we can just copy and paste this so we say that if the URL start with the user and then the role of the user is not user then again redirect user to slash off slash login with a custom message that you are not logged in and that's it for the authorization part it's that simple we just have to check if our URL or address of our page start with the admin and if so check if the role of our user is the proper one and if it's not then redirect the user to the login page and after row we want to run this middleware for these routes in our application just as before so that's it for the authorization part okay let me now run our server and open up my browser if I click on the user panel because I'm not logged in I'm headed to the login page and if I log in with the user1 hit the login button again if I click on the user panel now I can access to the user panel but if I click on the admin panel because I'm not authorized I'm not the admin user I headed to the login page so essentially this line of code is now running so if I log in with the admin now I can access the admin panel so again if I sign out and want to go to the user panel you can see that I'm headed to the login page so the next thing I want to do in this application is to take care of writing this custom message above the login page so here I go back to the vs code and go to the app slash auth slash login page and here I want to define a interface for the shape of the props for the login page so I'm going to say interface for I perhaps and then search params which is a object with its keys are string and the values are string or a list of string or undefined so here we destructure the search programs from the props of the login page and then here in the jsx I'm going to say if these search params that message is existed then when they're a parameter for us which contains the search problems that message if you want to know from where this message comes in go to the middleware and here you can see that we set a query for this login URL with the name of message so I go back to the login page and say if the search param stock message is existed then render a parameter with these search params doc message so this how it works in the Nexus version 13. and in this way you can extract the important problems from the props of a page and if I save this and go to the browser and log in with the normal user go to the user panel it's okay but if I go to the admin panel we can see the you are not authorized message here in the login page so in this way we can send a custom message from the middleware into the login page the last thing I'm going to do in this video is to give you a practical example of how we can include our access token inside the HTTP requests that are being sent to the backend so the access token I'm talking about is this access token that we have retrieved from our backend API and here I have an another backend API which is slash user and then the name of our user this API gives the information about the user that we are sending its username as in param into this backend API so if I go ahead and send this get request the response is an unauthorized 401 message that says I'm not authorized to call this API so in order to call this API we have to include this access token inside our request to this slash user slash username API so let's do it in action this is this scenario we have a button here and then we click on it it retrieves the user information from the backend API that we just talked about and it doesn't get a 401 unauthorized message because it includes the access token inside the HTTP request that is being sent to the backend API so let's implement this in action so I switch back again into the vs code and go to the app folder slash admin slash panel and open the page.tsx file and the first thing you want to do is to retrieve the session from the use session and then if I understate that contains our user data which its type is the user interface that we have defined in the beginning of this video so in order to use you state in this page you have to mark this page with the use client annotation and then we are going to define a function called Fetch user profile so I'm going to say const fetch user profile and this is a async function and here we're going to say const res equal to a weight which API and then grab the address of this backend API from insomnia then paste it here and here inside the name of the user use a template literal which says that session dot user dot username then we're going to say the method of this request is get and then we set the headers which says its content type is apps application slash Json and the most important one is here we're going to say that authorization and set it to a string which starts with Bearer this is very important you have to exactly say the Burr in the beginning of your string and then put the access token that we store in our session so I'm going to say session this session again is come from the U session from next off so I'm going to say session user and then access token so in this way we include the access token that we retrieve from the backend login API inside this fetch request to the slash user slash username API for again from the backend so the next thing we're going to say const data equals to a weight or is that Json and then set the user data from the data that we retrieved from this backend API and here in the jsx we're going to add a button here which calls this fetch user profile so let's import the button and then render the user data into the screen so let's save this and go to the browser and if I click on the user profile you can see that we are getting the right information from that backend API so again if I go back to the vs code and here in the authorization slightly distort this access token or better starter save this and open up my console and again send the request you can see that we get a 401 unauthorized response from this backend API again if I go back to the vs code and fix this Bearer token now if I click this you can see that the information properly without any error and yeah we have successfully implemented the authorization with next auth in next is version 13 and also we got the idea of how we can store our backend access tokens inside the next auth session and how to include them inside the requests that are being sent into the backend apis so till the next video bye bye
Info
Channel: Sakura Dev
Views: 31,045
Rating: undefined out of 5
Keywords: authorization with next-auth, role based authorization in nextjs 13 and next-auth, next js, next js 13, next auth, next auth app dir, next-auth jwt, next-auth/middleware, next-auth tutorial, next-auth credentials, next-auth custom login page
Id: xJ6efexXJ7I
Channel Id: undefined
Length: 20min 52sec (1252 seconds)
Published: Thu Jan 12 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.