Laravel Sanctum SPA Tutorial - React SPA Authentication With Sanctum

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys in my last video i spoke about laravel api authentication where i discussed when to use larval sanctum over laravel passport and when to use token-based authentication instead of sessions today i will be showing you how to authenticate your next.js sba using liable sanctum's cookie based session authentication i already set up a very minimal project for this video that basically displays a list of tickets on the dashboard sorted by the highest priority our goal is to add the authentication so that the user is only able to get to the dashboard and see the tickets if they are logged in [Music] first thing we need to do is install laravel sanctum then publish configuration and migration files and then migrate the database my api is running in a docker container so i have to run this command there while laravel sanctum is being installed let's go over this api quick so within my api routes i only have a single route that basically fetches the tickets this is the route that we're going to be adding authentication to within my web routes i only have two endpoints one is to log in and the other one is to log the user out let's go ahead and publish the configuration let's migrate the database and i think we're good to go because we will be authenticating our sba we need to add this middleware to our api middleware group let's open the kernel class and add it right here and what this middleware does is actually very similar to the web middleware group first it overwrites some of the session parameters such as http only and same site and then it runs through more middleware if the request is coming from your own sba it encrypts cookies then it adds cookies to the response then it starts the session and verify csr token so let's add the protection to our api route that would be middleware or sanctum and now if we try to load the page we should get an error and we get 401 which means the user is not authenticated because we're trying to authenticate our first party spa we need to specify that domain within our sanctum configuration file so let's open the config file and this is the variable that we need to set this basically has to be set to your sba domain so for example if you're running your api on a subdomain something like api myawesomedomain.com and your sba is running on my awesomedomain.com then my awesome domain would be the value that you would set this environment variable too in order for stateful authentication to work your api and your spa top level domain must match so in this case this and this should be the same if you had your sp or ap on a different domain something like another domain.com then this would not work because they would not share the session for local environments if you're running it on a different port than this you need to specify that port in my case i'm running my spa on localhost 3000 so let me add that to the env file localhost 3000 and also we need to set the session domain in order for stateful authentication to work the sba and api domains need to share a session id and for that to work we need to specify the session domain this would be your top level domain which in my case is just localhost but if we use the same previous example then this would be my dot awesomedomain.com prefixed by the dot and that means that any sub domain and the domain itself will share the session id so i'm going to change this back to localhost and you should be good enough now if we go back to the documentation within the course and cookies section our course configuration needs to return this header with the value of true and to do that we need to set the support credentials to true and also we need to set with credentials to true for our axios instance so let's go ahead and add that first within the course config file on marvel api so i'm going to open the course dot php set this to true and note here that the paths parameter only allows api routes to go through so you need to specify any routes that you want to be allowed as well in my case that is login and logout because my login and logout routes are within the web routes file and not within the api routes file if in your case your login and logout are within the api so it's something like api slash login then you don't need this so let's try to log in now and see what happens and we get 419 csr token mismatch which is expected because we haven't passed any tokens to the request and marvel's built-in csr protection kicks in and blocks our request in order to fix this we need a way to access the csrf token to do that we need to make an initial request to laravels api which will initialize the csr token let's go back to the documentation and see how that's done we need to make the initial request to this endpoint it simply creates an encrypted csrf token and stores it in xsrf top and cookie and then libraries like axios automatically pass that on every request so let's go ahead and add this part to our login component and we need to add it right here since we don't care for the response we can just change this to that let's also add some response handling here that if it's successful we can redirect and if it's not we could cancel log the result so we need to check if response data error then we could console.log response data error otherwise we could console.log success we will worry about the redirect in a bit i also forgot to change this to api so let's try to sign in now let's enter our credentials and we're back to course error that's because this route is not allowed so if we go back to the course configuration file we only allow api routes login and log out so we just need to add that here let's try to log in now and now we're getting invalid credentials let me clear that out try that again invalid credential so that means that we're hitting the api no csrf issues no cores issues everything is working now we just need the correct credentials so let me enter the correct credentials actually before i do that let me show you that within the application xsrf token was initialized this is the cookie that gets created when the initial request is sent to this endpoint so let's try to log in now with the real password see what we get and we're logged in what we need to do now is store the login state somewhere on our sba so we don't have to make any additional api requests to check if user is logged in or not especially after user refreshes or browsers through the pages there are a few ways to do this we could either store this flag within the local storage we could store it in a session storage or we could create a custom cookie i'm going to create a custom cookie because it's easier to redirect user before hitting the client side from next js and avoid the flash of the unauthorized page i already have utility functions that handle login logout and is logged in checks so let's go and review that i'm going to remove this and put login in here and let's go and see what that does so the login function here basically just creates a custom cookie with the value of true and redirects to the dashboard the logout removes that cookie and redirects the login page and this logged in function simply checks that cookie it will first try to check it on a client side if it's not said then it will try to check it on the server side this is useful because sometimes we may want to check if user is logged in or not before any client-side components are rendered let's try to sign in now and let's confirm that we don't have that cookie in here and after we hit sign in we are redirected to the dashboard it loads the tickets which means that we're logged in and the cookie is created successfully here now you might be wondering what if user manually creates this cookie or manually sets it to true wouldn't the user be considered logged in the answer to that is yes the sba will think that a user is logged in but as soon as it hits the api the api will return 401 unauthenticated because laravel sanctum will handle the authentication on the api side so technically they wouldn't be getting any useful data but to have better ui and ux we could actually easily hook into axios via interceptors and catch such errors on any api request and manually delete the cookie and send the user to login page let's go ahead and do that on our apa.js file so i'm going to do api dot interceptors dot response dot use response response and then for errors we're going to check if error dot response dot status is 401 then we could do the logout that we just went over with and return the promise reject oops otherwise return the promise reject with there so now even if user manually sets that cookie they will be redirected to the login page as soon as the first api request is made so let's try to test that so right now we're logged in so let's remove the laravel session and refresh the page so we should technically not be logged in anymore and as you notice we are redirected to the login page and the custom cookie was successfully removed so now we could try to log in again but instead of trying to log in let's manually set the cookie to true and let's go to the dashboard page let's see what happens and as you see we saw the flash of the dashboard page and we were redirected to the login page and this returns 401 and everything seems to be working now i still don't like that flash of the dashboard page we could improve that i want the user to be redirected to the login page before they see any components to be able to do that we need is logged in flag within our components let's go back to the spa there are a few ways we could get is logged in flag on the components you could use a custom react hook using a context you could check within the components use effect call whether user is logged in or not or the one that i like is using higher order component kind of like a middleware so that i could pick which pages need authentication and which do not i already have the higher order component with auth created all i need to do is add this to the dashboard page it uses the get initial props and checks if user is logged in using the server cookies and this method we already went over with and if user is now logged in it simply redirects to the login page and returns user object with the is logged in flag you could pass any additional properties here and those will be available within your components so we could go back to the layout.js file and where we're exporting the default we could say with auth and that should work now if i try to visit the dashboard page you should be redirecting me before i see anything and that seems like it's working let's log in to make sure that everything still works and we're logged in the page refresh works correctly we just need to replace the sign in button with the sign up and that's actually very simple to implement now because we have access to these logins live within our components so let's go back to our spa and within the layout now we have access to user prop that is passed down from the without higher order component and we can pass that down to authenticator as an is logged in plug and in here we can say if is not logged in then return sign out link instead of the sign in so if not logged in return and this will have a custom on click handler that basically calls our laravel api to the logout on the server side so we can call logo route and then on success we can do clients out logout which basically removes the cookie and redirects to the login page so let's test it out to make sure that this works and we see the sign out button right now instead of the sign in let's change that to the cursor that looks good and if we hit this it should block us out and it did we're back to the login page if we try to access the dashboard page we can no longer do that let's try to log in and that's it thanks for watching guys please hit like and subscribe to my channel and i will see you on the next video
Info
Channel: Program With Gio
Views: 13,020
Rating: 4.9703703 out of 5
Keywords: laravel, laravel spa, laravel react, laravel api, laravel sanctum spa, laravel spa authentication
Id: uPKd3q-iaVs
Channel Id: undefined
Length: 14min 27sec (867 seconds)
Published: Tue Oct 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.