Authentication with Next Auth and Next.js 13

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone what's going on in this  video we are going to take a look at   how we can integrate the next of  package with the Nexus version 13. so these are the topics that we are going to cover  in this video first of all we we are going to set   up the next off package with the nexjs version 13  and then apply the credential provider into the   authentication system credential provider means  that we are just using password to authenticate   the users and then we apply sign in and sign out  functionality in our components and also we want   to use a next off middleware to protect some of  the routes of our application this is the final   form of application that we are going to create  today this application has three pages home admin   and panel the home page everyone can see it but  the admin and panel in order to access them you   have to be authenticated or logged in so if I go  ahead and click on the add new page here you can   see that we are forwarded into the login page so  I'm going to enter my username and password Here foreign here which means I'm currently logged into the  application now if I click on the admin link here   I can access to the admin protected page  because I am logged in if I sign out   and then go to the home page again to  the admin page you can see automatically   we are forwarded to the login page I think it's  enough with the introduction and let's go for it I open up my visual studio code and here  I have a nexjs version 13 application I   have enabled the app directory in this  project through the next.config.js file   and in the Pages directory I don't have any  Pages here but instead in the app directory   I have created four pages one the home page it's  just a empty page with a custom message that says   this is a home page everyone can see it that's it  and also I have a root layout which has a app or   here and if I go to the upper I have three links  in the upper one for the home page one for the   admin page and one for the slash admin slash panel  page the admin page is also a just an empty page   with a custom message just says admin protected  page and also admin slash panel it's just a   empty page with deep protected page just these  messages and also I have a slash auth login page with just a regular form with two text box   one for the username and one for the password and  then a button which in the on click event of this   button I call on submit function it's just an  empty function and also I have two user one for   the username and one for the password which I  have bound to the text boxes of this phone the   reason that I have used ref here instead of used  it is because I don't want this page re-render on   every input changes and these two text boxes but I  know this is not a good idea to create a to create   a form using UCF or use State you should use  libraries like formic react hook forms but in this   video we're not going to cover them so we just use  the easy way so the first thing I want to do here   is to install next auth package so I open up my  terminal and just type npm install next dash off   and because I have already installed this  package I'm not going to hit enter here   so I close this off to add NYX Earth into our  project we have to create a file called Next   off.ts just like this into the pages slash API  slash auth directory in our application this   file contains a dynamic root Handler which  handle so all the requests that comes from   slash API slash off this file also contains the  global configuration for the next off package   so I go to the Pages directory and here inside  the API I'm going to create a folder name off   and then in this folder I'm going  to create a dot dot next off.ts   I go to the documentation of the next auth  here and inside the getting started page   I found the initial codes of the next auth file so  I copy them and go back to the vs code and paste   them in the next auth file here and here in the  provider list just get rid of the GitHub provider   here and also this line and since I am using  the tab script I'm going to give it a type here   next of options and import it from the next  half so now it gives me the auto completion   for the configuration of this file next thing we  have to choose a provider for our authentication   system essentially providers are a are services  that allows user to sign into our application of   course we can have more than just one provider so  I go back to the next half documentation and here   inside the provider section of the documentation  we can see the all providers that are supported   within the next half authentication system the  provider that we are going to talk about in this   video is the credentials so credentials provider  allows user to log into the application with just   a username and password so here I just copy and  paste the credential providers that is provided   as an example in this page and go back to the next  of the TS file and paste the credential providers   inside the provider list and then I import the  credential Provider from the next auth and here we   get an error it's because we have to remove these  curly braces for the credential providers import   so now the arrow is gone here we have a name  for our providers and here we have a credentials   object which defines the username and password  so in order to sign in through the credentials   provider user must have a username and password  you can see that the label for the username and   also for the password and it's just because Nix  off can automatically create the login form for   you so you can specify the label for the username  and label for the password and also the type of   the input inside the login form in this tutorial  we're not going to use default form of login   for the cred credentials we are going to use our  own custom login for for the sign-in of the user   so the next thing and most important thing  in this credential provider we have the   authorized function so essentially when we call  sign-in function which provided by the next auth   this authorized function will be called in  this function we can find our user from the   backend database and then check if the user  is found and its usernames and password are   valid then we return the user and else if the  username and password are not valid return now   so when we're returning now from this authorized  function essentially we reject the request for   login to our application through the next  auth so now let me clear this dummy user   authentication here and replace it with a real  world example so here the first thing we want to   do is to destructure the username and password  from the this credential here so I say trans   username and also password equals to credentials  and to get rid of this Arrow here we say as any   and then we send the username and password  to a post request to our backend like this   we use Fetch and send the username and password  in the body of our post request to this backend   API so this backend API essentially handled the  plugins for me it takes username and password   and in the backend just check the if the user and  password is correct Returns the user information   along with a jwlt token and then we are going to  say const user equals to a weight res dot Json   and then say if res that okay and also  there is a user then return the user   else just return now in order to show you what  we can get from this API here when we send a new   correct username and password let me test this  API inside the insomnia so insomnia it's just   like a postman so here we send a post request  here to the auth that login of this backend   API and send the username with my name and a dummy  password which already has been set in the backend   so if I send the this post request here you can  see that the response is the information of the   user and also it has a access token so we can  use this access token further to access to the   protected API of our backend so it's a back-end  stuff we're not going to go through them just know   that when we send the correct username password  this backend API gives us information about the   user and also a access token which we have to tour  in the next half in the front end in the next JS   and then we can use it when we want to request  through the protected APR route of our backend   so let's go back to the vs code again and here  after the provider list here so this is the list   of the providers after that we are going to say  the strategy of our session so here we say session   say strategy and say to JWT as you can see we  have two strategy for this use for storing our   session database and JWT so JWT is a bit more  straightforward we don't need a database in the   next JS project to store the session for us we  are going to select the agility for the strategy   of our storing our session in the authentication  system so I think that's it for the next auth.ts   file here and now we are going to use the sign  in functionality and sign out functionality in   our app directory pages so I think that's it  for the configuration here for now and let's   go to the app directory here and Leverage The  Power of next auth package into our application   but before doing that note that the Nexus version  13 the API wrapped still needs to be in the Pages   directory not the app directory so we have created  the next auth.ts file inside the Pages directory   and the next thing you should consider is that in  order to access to this session which contains the   information about the logged in user we have to  wrap our Pages inside the app directory with a   session provider so I go to the root layout  of our application and here I add a session   to the iprop interface of the root layout and set  its type to any and then we can get the session   from the props of the root layout and here we  can wrap the pages with a session provider which   comes from the next auth slash react so I say  session provider and wrap the pages with the   session provider and set the session props of  this session provider to this session which we   have extracted from the props of the root layout  so next up automatically send the session to the   root layout we just have to extract it from  the props and send it to the session provider in the next S12 we use the session provider  in the underscore app.tsx but in the next JS   version 13 in app directory stuff we have to  use it in the root layout now let me run the   development server to see if there is an error  so far you can run Dev okay we don't have any   error yet now we can go through the protected  page even though the user is not logged in so   let's quickly add a sign in button here inside the  this app of component so I go back to the vs code and go to the app or component and here in the top  we can now access to the session so we say const   use session and extract the data out of  it and let's rename it to the session   and here in the jsx to speed up the process we  just copy and paste some of the j6 it is needed   for the assigning button so here essentially  added this div here we say if this session exists   which means the user is locked in and in this  session there is a user now render this section   so this section is going to have username and  also a sign button which in the unclick event of   it we call sign out function which comes from the  next auth so let's import it from the next half   slash react and if the session is not available  which means that the user is not logged in show   a button with a sign name and in the on click  event of it call the sign in function which again   comes from the next off slash react so that's  it so let's save this and go back to our browser   and here we can see that we have a sign button  here so if I click on this we will be forwarded   to a login page which has been created by the next  auth automatically so to use our custom login page   we have to go to the next of configuration  file in the pages slash API slash off   and here at the end of it we are  going to add a property name pages   and inside the pages object we set the  address of our sign-in form so I say sign in   and set the path of our sign-in form the sign-in  form of our application is inside the app slash   off slash login so I say slash off slash login so  if I save this and go back to the browser set back   if I click on this sign in now we are forwarded  to the custom login page that we created ourselves   not just the one that is created by DNX auth so  now let's implement the sign in functionality   inside the custom login page go to the slash off  slash login and open up the login page and here   you can see that after clicking the login button  the unsubmit function is called so inside the   unsubmit function so inside the unsubmit function  we just have to call the sign in function which   comes from the next auth package so here we  say current result equals to weight sign in   and this time we have to pass two arguments one  the name of our provider which is credential   and the other is the is an object that contains  our username and password so here we say username   and set it to this username state so it's  a username got current since it's a user   and also password and say to pass the current  which contains the user password and we set   redirect it true because we want to redirect  the user after the sign in function is complete   and then set callback URL to our home page  so now when we call this sign-in function   with the name of provider and the object which  contains the username and password we actually calling this authorized function here so this function in turn extract the username  password from the credentials object and then   send it to the backend API and check if the  user is returned with the backend information   and the response is okay send the user to the  session and else return null to the session   so here in the upper we can check the session  if the if there is a session it's not it's not   now and if there is a user in in inside it we  can say that the user is logged in and we can   access to the username of the current user and  now let me go back to the browser and test it   so here in the login page I  enter my username password hit the like button here and we have redirected to  the home page and here we can see that my name is   on the app or and the sign in button is turned  to the sign out and if I click on this sign out   button you can see that the user is now logged out  and the username is now gone so again if I sign in you can see that my name is now on the app bar  and let me go back to the app or section here and show you how we can access to the username  so essentially here we say that if the session   exists and there is a user inside it show the  username and show a button with the sign out   functionality and if this session is undefined  or null show the assignment button which means   that the user is not logged in or sign out okay so  far so good go back to the browser sign them out   and click on the admin page making  access to the admin protected page   even if we haven't signed in  so let's handle this problem in this section we are going to take advantage  of the next auth middleware to protect some of   the routes of our application so let's get into  it I'll go back to the vs code and all I have   to do is to go to the root directory of our  project and create a file name middleware.ts and inside this middleware.ts I export the default  middleware from the next Earth middleware and   Export a config object or a matchup property that  says which route you want to protect so in this   matter array I will Define my protected routes  so I say slash admin for example which means   that I want to protect the slash admin route  from the unsigned user so I save this and go   back to the browser to test it so here I'm in the  home page and if I click on the admin link here   again several that's because in order to use next  off middleware we have to Define next of a secret   in the environment variable file so I go back to  the vs code and go to the that EnV file and here   I put the next half underscore secret to a random  string and also we have to define a next auth   underscore URL to the root domain of our project  we are running our project in a development   server so we have to specify the address of the  development server in the production you have to   specify the root domain in which your project is  running so I save this and go back to the browser   and refresh the page go back to the  home and again click on the admin   and here we go we are forwarded to the login  page and if I log in now I'm logging here   and if I now go to the admin page we can access to  the admin page because we're now login I sign out go to the home again go to the admin page  here we go we are now again forwarded to   the login page because we're not logged in  and next off doesn't allow unsigned user to   go to the protected page so now if I click on  the panel I can still access to the panel page   and this panel page is under the slash admin  routes so I go back to the vs code and inside   the middleware we can specify another route here  click slash admin slash panel and this works but here we can specify that all other sub routes  of the admin route must be protected so I say   dot path add a star on the end of it  and save this now go back to the EVS   code or go to the home and directly go to  the panel and here we go we are forwarded   to the login page because we're not logging  so let's log in and again click on the panel   now we can access to the panel page because  we are logged in to make sure sign out go to the home click on the panel we are headed to the login page logged in again now go to the panel we can access to the  panel page because we have specified that   all of the sub routes under the  admin routes must be protected   so I think that's it for today and before ending  this video let me quickly recap what we have done   in this video first of all we install the Nexus  package and then created a Nexus Dynamic route   inside the pages API folder and in this file  we said that we want to use credential provider   and so we added a credential provider with the  credential username password and then we specify   a function called authorize and this function  takes a credentials argument and then inside it we   extract the username password from the credentials  and send them to the backend API which checks if   a user with this username and password exists  we send this response which contains the user   to the session and if the username doesn't  exist we just return null to this session   and then we specify the Jade ability strategy  for persisting our session in this server   and also we specify that we want to use slash  off slash login page when we call the sign-in   function without any parameters and then  we go to the login page of that login here   we created a form with user and password and  then call on the on submit event of the form   we call the sign-in function which comes from  the next auth and here specify that we want   to use credentials and then send the username  and password to this function and also set the   redirect true and a callback URL to our root route  our project and that's it and inside the upper we   can access to the user session which this use  session returns session which in turn contain   the user information if the user is logged in  decision is existed which is not undefined and   inside this session there is a user object and if  the user is not logged in the session is undefined   so in that way we can we can find that if the  user is now logged in to our application or not   and one thing you should uh consider here in  order to you to access to the use session your   component needs to be a client component we didn't  specify use client here because in the root layout   our our app directory we use use client here so  now all of our components are client components   we use a use client here because this session  provider needs to be in a client component in   order to work correctly so I think that's it  for today and uh in the next video I have a   surprise for you so be sure to subscribe to the  channel stay tuned for the next video bye bye
Info
Channel: Sakura Dev
Views: 91,427
Rating: undefined out of 5
Keywords: 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: cDWytA0V2kI
Channel Id: undefined
Length: 27min 6sec (1626 seconds)
Published: Tue Dec 20 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.