How I Created Laravel And Vue Authentication: API + SPA

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Thanks for the video.

I watched this and also Andre Madarang's Laracast video: https://laracasts.com/series/whats-new-in-laravel-7/episodes/6

In Andre's video he mentions that both the SPA and laravel backend need to be running under the same domain. Is that true?

What is the best practice if I wanted to host my SPA on an S3 bucket and the laravel app (for api endpoints) on a server?

👍︎︎ 2 👤︎︎ u/create_creators 📅︎︎ Jan 03 2021 🗫︎ replies
Captions
hi in this video you're going to learn how to build an user authentication layer for your single page application using laravel and ugs before we start i created two separate applications you just single page application on a front end and a laravel application on the back end they're both running locally on my laptop so let's go to the front end of our application if we go to browser we can see that we have a login component with a simple form and we have a post page which calls a back-end api and retrieves the data so if you go to the post component source use post index we can see that we import the repository module at the top and when it this component is mounted we call that getpost method get a response and update our post object if you look at the getpost method it's a simple get called our backend and you can see at the top the important api module which is basically an access wrapper so if you go back to our post page we can see it's accessible by anyone so let's put it under authentication layer so only logged in users can access it so let's jump to the back end okay let's go to the routes and as you can see we only have one route it's get to the post and if you go to a post controller we can see it basically returns an array of values now we can start building the login logic let's create a login route and a controller here you can see a simple login method here you can see we created a basic login method and we provided the email and password and we use the off facade and basically what the attempt method does is behind the scenes it will go to the users table and search for the user with provided email and if the user is found the hash password stored in the database will be compared with the password value passed to the credentials array so this one um also we don't need to hash his password here because the attempt method will do that for us and they fit two passwords passwords match and authenticated session will be started for the user so and if the credentials are invalid we just abort which basically throws an exception while we're at it we can create a logout action as well so again we use logout method for off facade and this will clear the authentication information in the user session we should also create an end point for the log out action and we should import the login controller here in our routes now we can install the laravel sanctum package this package offers a simple way to authenticate users using laravel's built-in cookie based session authentication services so i'm just going to follow the official documentation and first of all install the package using composer now we should also publish the configuration files using this command and let's add sanctum's middleware to the api middleware group so if you go to http slash kernel uh we should add a this value right here for now i will skip this step because it's not necessary if you go back to our routes now we can add a sanctum guard to the post route so this guard will ensure that the coming requests are authenticated so middle now we need to change session and course configuration settings so it allows requests from our ugs single page application let's go to the config slash sanctum and if you don't see this file make sure to run the publish command because it creates the config configuration file so inside the config we need to price sanctum stateful domains so that requests coming from provider domains can receive authentication cookies we do this in our environment file so if you go to we have to change the so as you can see you can pass multiple domains using the comma symbol and you should also provide the part so my front and front end is running on the 8081 so i provided it right here oh i say melee title composed yes and for production you should pass a valid domain now we should go to the session configuration so session.php in our case we are using the sessiondriver file as you can see here we should also set a session domain so if you go to session domain let's set this value to localhost so because our frontend application is running on localhost i've set the session domain variable to localhost in my environment file let's go back to the session configuration and let's find the secure variable um we also have to change the secure option because our front-end application is not running on the https connection so let's set the session secure cookie to false in our dev environment we're almost finished with our configuration let's go to the course.php config and make sure to change the supports credentials to true and set the path to apes slash star and sanctum but slash csrf cookie so the backend is ready now we have to configure the front end if we go to the post view and we can see that it no longer fetches the posts and gets an error this means that our backend is protected and working properly so let's create a login logic in our login component so let's open the login component here you can see that we have a two inputs binded to a user model we have a few paragraphs which indicate loading state or show errors we also have a login button which when clicked we'll call this login method which is currently empty so let's start writing our login method so here we are using the ivx for our vue.js application and we are calling the login action inside our vx store and we are passing the user model of course the login action does not exist yet so let's create it so let's go to the store index.js and at the top we have to import the repository module which will contain all the back-end routes so let's import it so if you go to this module we can see that it at the moment has only one route get post so let's add the login endpoints so notice we have created a create session endpoint and it is automatically provided by laravel sanctum package and this will be later needed for the login endpoint so at the top you can see the api module which is a global access wrapper and we need to change some settings here so first of all let's make sure that actions with credentials or settings is set to true this is needed for our course configuration we should also configure the interceptors for each request and response so let's start with the request interceptors first some instance so these request interceptors will be run before each call to the back end and here we set two headers accept and content type to application json so now let's create on the response interceptor so we also created a response interceptor that will come in handy later now let's return back to the store module and create an authentication module so if we go to the storeindex.js let's create an authentication module so first we define a defined state okay so we will store our authenticated user inside the state and other components will access the user data using the getters defined here so we also define the getter authenticated which will tell if there is an user in in the state we also created a mutation set user to update the user values tape finally we created a login action which will call the backend and log the user in inside our login action you can see that we first have to call the create session endpoint and only then call the login endpoint that's because during the request arvel will set the xsrf token cookie containing the current csrf token so the token will be automatically passed inside action's headers on subsequent requests so yeah so once that csrf protection is initialized we call the login endpoint and on successful login request the user will be authenticated and subsequent requests will be automatically authenticated using the session cookie that laravel issued to the client so let's create an user record in the database and let's test the login component i will use the php artisan tinker for it and run the factory command so we can see a new user record inside our database so now that we have created an user we should test the login endpoint if everything is working correctly after a successful request to the login endpoint we should be redirected to the post page so let's test it success uh we can also see the authenticated getters set to true inside their view devtools um so the state we can see that authenticated is set to true and we have a user object right here and there are still a few problems even though we are logged in we can still go to the login page and if you deleted the cookies so let's delete the cookies we can still access the post page which is bad we we want to protect this page and if user is not logged in to not allow him to reach his page so let's create a middleware which protects an authenticated users from reaching this page so let's create a new folder inside router and call it middleware it should also contain a new folder called rules and let's create a few rules the first one is user.js so created a user role which basically checks the store getters and if the authenticated getter returns true it means that we have an authenticated user in the state so meaning the request can pass through and if the authenticated is false we just redirect the user to the login page so now let's create a guest rule um here we inverse the user role if user is authenticated we redirect him to the post page and else we pass the request to now let's create a global middleware called index.js which will import both obvious rules and now we can apply this middleware to our route so if we go to rouse.gs let's import the middleware and let's apply apply the middleware to our routes let's go back to the browser if you try clicking on the on the links nothing happens because we are unauthenticated so let's try to log in and see if we can access the post page so now we are in the post page and we can't access the login page which is good we can now update our navigation so logged in users don't see the login link and the guests do not see the post so inside the app.view let's import the map gutters from the ux and this way we can access the authenticated property from the global of state let's use this computer property inside our template and hide the buttons so the login should be hidden if they authenticated as false and if the user is logged in you should see the post yeah so now we can't see the irrelevant links but if you try to refresh a page as you can see we are still redirected to the login page so the user inside our view store is getting delete on refresh we can solve this problem by putting the user object inside the session storage and this way we won't lose our user data on the refresh so let's go to the store and login action store and login action and after successful login let's add the user data to the storage we can also update the default user value in the state to first check if there is an user in the session storage so let's do that and now let's try to login so as you can see we have an user object in tower state and if you refresh a page the user won't be deleted and the ux will access the user from the state and so as you can see we still have the user however using this approach we may run into the problem when the session expires on the back end but the user exists in the session storage on the front end so we have to fix this and so let's let's do that by going to the axios settings and we will use the response interceptors so basically what we'll do is we'll check the error status you get from the back end and if the status is 401 meaning that we have an authenticated on authorized request we will delete the user from the session storage so let's do that and we will also call a window dot cash dot load so if we receive the forward status we delete the user from the session storage and we also reload the page and this will trigger the route middleware which will not find the user in the state and will redirect the login page so it basically will trigger this middleware so the authentication layer is almost complete we only need to create the logout button so let's add it and let's create the logout method so so the way this will work is we will dispatch the logout action to our of module which don't exist yet so we need to create it i think log out we shall call the logout endpoint in the backend and set the user inside the c to null and we also can delete the user from the session storage so now we can test it as you can see the request returned status code 200 and we can check inside the session storage there is no user so that's pretty much it i hope you find this video helpful and see you on the next one
Info
Channel: Simon Poska
Views: 17,133
Rating: undefined out of 5
Keywords: laravel vuejs authentication, laravel and SPA authentication, laravel and vue auth, API + SPA authentication, vue session based authentication, how to create authentication, vuejs and laravel authentication 2020, laravel and vue login, vuejs laravel session based login, vue js cookie based login, login using laravel and vuejs, login using laravel and SPA, laravel sanctum login, authenticate users using laravel sanctum and vuejs, laravel authentication for beginners, laravel+vue
Id: BWNcuB3LQz8
Channel Id: undefined
Length: 21min 55sec (1315 seconds)
Published: Mon Nov 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.