#1: SPA Authentication using Laravel Sanctum (formerly Laravel Airlock) Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello developers welcome to the channel now laravel seven is officially released on 3rd March and on this page you can see the all new features added into this laravel 7 I will put the link of it in the video description you can check this out now I am going to start a new series on what's new laravel 7 in this series I will explain key features added into the level 7 so if you are new to this channel hit that subscribe button and make sure to press Bell icon so when I upload new videos you get notified now let's start with today's video here on this list the first feature is the laravel sanctum so let's see the documentation of sanctum this laravel sanctum is a lightweight authentication package for developing single page application mobile application or for simple token based API initially when this package was released its name was here log and now tailor Rodwell has renamed it to sanctum because of trademark dispute using this package you can implement authentication in two ways one is the API token based authentication and second is the SP authentication in the token-based authentication we issue a token to authenticate the user and a user may have multiple tokens in this SP authentication we don't need tokens instead it uses levels built in cookie based session authentication and provides the benefit of CSR of protection session authentication as well as products against leakage of authentication credentials via cross-site scripting today in this video I will explain this spi authentication and in the next video I will explain this API token authentication to explain this SP authentication I have already created view app using view CLI less it is in the terminal here on this side of the terminal I am in the view app that I have created using view CLI and on this side of the terminal I mean the laravel app that is the fresh installation of the laravel 7 so let's see the app so here I'll turn and PM dancer now let's open this URL here it is I have simple homepage and I have created this login page register dashboard and this link to log out the user this is all simple static pages now let's see this in the editor in the source directory in the main door jeaious here I have imported the bootstrap library and boots of CSS next in the routes index dot GS here is the routes for home page login page register and dashboard next check in the components navigation dot view here is the navigation bar and the views directory here the dashboard view is a simple HTML markup nothing else and here is the home view for the home page this is the login view for the login page and register view for the register page very simple actual markup in the view app now we will implement authentication using laravel centum for that we will need to install laravel centum right here indeed laravel app let's go to documentation we will run this composer command in the terminal right here now in this package is installed now let's see the next step next we need to run this vendor publish command it has published the migration and sanctum configuration file let's open this in the predator now I have opened the two auditors in this editor we have laravel app and in this editor we have view app now I have changed the color of the editor so you can easily identify that this editor is for the view app and deciliter is for the laravel app next it has published the database migration this personal access tokens table migration because we are using SP Earth integration so we don't need the X migration anyway let's keep it here I will use this table in the next video when I will explain token-based authentication next it has published the config sanctum configuration file and here this stateful option is very important this stateful option will determines which domain will maintain stateful authentication using laravel session cookie when making requests to the API we can define the state whole domain using this environment variable in the dot env file and also remember that your front-end app and back in API s-- must be on same domain for example let's say your front-end app is running on example.com and the back in API is running on API comm in that case SPI authentication will not work both domain must be the same so if your front-end app is running on this example.com then your API domain can be on subdomain for example API dot example.com in this example this will work because both are on same domain example.com and here sanctum stateful domains will be example.com in our case both front-end and API are running on localhost and it has already defined this localhost in default value so we can skip this environment variable in the dotty and we file another option you have to define is the session domain this one and default value is null we are on localhost so we can skip it but when you have domain for your app you need to define it like this example.com and if you want to use authentication for multiple subdomains then you can define it like this dot example.com now it will share the session ID with all subdomains so we can skip it because we are running on localhost now let's see the next step next we need to run the migration so I have already created database so let's go to the roti and we file yeah database name is sanctum and username is your lab password is password now let's go to terminal and on the migration PHP artisan migrate is the now let's see your next step next in the Colonel dot PHP we have to add this middleware so in the app HTTP Colonel dot php' right here we will add middleware and make sure to import class right here now if we see this middleware and it has used the encrypt cookie middleware that is also used in the web middleware right here next it has use the ad queued cookies to response middleware that is also used in the middle beard and third is the start session it is also used in the web middleware and it is using the verify CSRF token which is passed from the sanctum configuration file this one and it is the same right here so this middle wheel is using these three and this lease for middlewares in the API next we will implement the gestation feature so in the laravel app first I will create register API so in the API route and here I'll add post route register sister controller at register next we will create this register controller so in the terminal PHP artisan make controller register controller the HTTP controllers register controller here I will create method register and it will accept request dollar requests next I will validate request validate and we will pass fields to validate the home request first really is the name that is required second is the email that is also required and it must be email and it should be unique in users table next is the password it is also required and it's length will be minimum eight-letter and it should be confirmed next after validation here I'll create user create make sure to encode this use the model and arel create name request name and email is go the request email and the password is [Music] make you taller request password and make sure to import this ash right here next if you want you can return this created user in the a JSON response but I think it's okay in our case you don't need that so are the history API is ready next we will use this register IPE in DB web so the view app in the the digital view here on click this register button we will submit this form fields to the register API so first here I will create data and it will return form and the ass fields name initially it is empathy next it has email that is also empty password and password confirmation now we will bind these form fields with the input field so here here type is text not name now here we'll say V - model is equal to foam dot name and let's copy this and here in the email he'll say phone or email and here in the password will say chrome door password next in the password confirmation we will say password confirmation next next on click this button you will call the distal method so you can also say click dot prevent to prevent the default behavior of this button next we will create this register method and say methods and register method now in this method we will a be registered API for that we will need X here so in the terminal we will install X use and p.m. install axles now it's installed next here I want to mention that I have already created a tutorial on smart way to use ap ice on front-end framework I highly recommend you to volt that video also I will put the link of it in the video description to use EPA's imprinted app I always create a dedicated aps directory so here I'll create a new directory API s-- and here in this directory I will create API dot J's next here I will import xeo s-- from Axios and you'll say let API is equal to XE o dot create it should have curly brackets and then base URL here will pass the base URL of T or API server so that is here in the laravel app I will run PHP artisan search and here also run and p.m. from serve now let's copy this non Willard determine next we will add slash API in this URL I added this API because in the laravel app we have defined your route in the EPS route and in this route it automatically adds API to every route here is a steal issue because here our front-end app is running on localhost but in the view app we have defined this IP address in that case it is a different domain so here the laravel sanction will not allow the authentication so here instead of this localhost IP address here we'll need to add local host and then we will export default API that's done here next here we will create another file user dot GS this user DOJ's will contain the old API is related to user like register login and others so here I'll say import API from API and next here say export default and in this object we will define all the methods related to user API so here I'll add mister method it will accept the foam and then he'll return API doorpost to register route and then we pass from this form right here now in the register Dorp you here I'll import API is user and in the register method user dot register in this method we pass this dot foo now let's see this in the browser here let's open the inspector let's see fresh this let's open the inspector and in the network tab now if we hit this register button it has hit the history plate but we got 419 error if you see the city's see a syrup token mismatch so to fix this let's see the documentation here it is first we need to send the request to this path it will set the CSR a cookie on the browser and then we need to send that CSR cookie with every request so let's implement this so in the API is directly here we'll create another file CS r f dot GS general import api chrome API and next next port default home check and here I'll create method get cookie this method will say API dot cat this path 90 registered on pew here I'll also import he is C asada and in the resistor net right here we will say CSRF dot get cookie and then we'll hit the register API now hear this see a syrup dot get cookie will hit this route path and it will set the csro cookie in the browser and then we will send request to this to this user register but here it will still not work because because this route path except this domain domain.com and then sanctum CHR cookie but in the f8 or Jas we have set the base URL API so here it will be domain.com slash API slash and then same come CSR a cookie and which is incorrect path so it will give us 404 error plus in the browser refresh and you behave this it is sending bcs our cookie but here we get the 404 error here is the full path with api so how we will fix this so in the laravel app you go to render a directory and then in the laravel same time package source and then in the sanctum service provider if you scroll down right here it has defined the CSR cookie route path and here is the prefix sanctum so we can modify this sanctum prefix in the configuration file so in the config sanctum dot PHP right here we will say prefix API does done non DAV web here we can remove this now let's see this in the browser refresh clear now if we hate this mr. button it worked we get the 204 status it is hitting domain name then API slash CSRF cookies but after this csr of cookie it should hit the register route because we got the console error let's see this general property then of undefined so mr. view here it is correct less cdcs fara actually here we forget to return this now refresh we hit the register button it hate the csro cookie and then it has ad register path again we get it 419 error that is csr a broken mismatch that is because we are missing some configuration so if we see the documentation we also need to set these support credentials in the laravel app if we see the composer dot JSON file it has added the new default package that is fruitcake laravel course and that package handle Z cross origin resource sharing this package configuration files is in the config course dot PHP right here it has allowed the cross-origin resource sharing for all api is if you want to add more then you can add like this for example login here I will not use this because because I want to use only Pais using this API prefix which is already added here next here is the important configuration here we need to enable this to you we also need to enable this credential in the front-end app and we see documentation this one we need to copy this and we will add this in the API dot J's right here here instead of a cocl will say api dot defaults dot with credentials true des done here now let's go to browser refresh now this time if we hades register button now me get the 420 to edit that is validation added which is correct unless handle this validation so the register dot view here will say dot catch and then we'll say if error dot response dot stickers is equal to 422 and then we'll say this dot errors is equal to L dot response dot theta dot errors next we need to add this field in the data property right here and initially it is input array next every will print the values in errors so here I'll say pan and plus let's say because it is validation error let's say class says text dangered and we - if the dot name and then here we'll opinion start name at zero Dex I did this zero deaths because if you see error this name is an array next I'll copy this and paste it right here and here in a peridot email next here in the password add a dot password and right here password confirmation now let's see this in browser refresh now if we did this mr. button immediately we can see these validation errors next we need to handle this registration process so next what we will do when user a there is a button if you sponsor is successful then what we will do here we will say dot ten we will say this toward you told a router dot push to Logan doubt so here what we will do when user is successfully registered then we will redirect them to login page let's see for refresh now less resistant this may be a niche quad Alicia example.com password confirm password and it register now they start successfully and we are redirected to the login page now if we see the database here in the users table we have new user now we have reached to the user successfully here in the Eastern method first we get this CSR pookie and then we hit the register API it's fine here I don't want this get cookie in this register method instead I want like this and this user register matter should handle the CSR of cookie so how we can implement this so in the user dot GS but here we will do here a limp or see a setup next here we will say this method is a sink method and then you'll say a v8 CSRF dot cat cookie and then we will send the the history pay like this now here what this async method we'll do it we'll wait for the CSRF cat cookie when it is successful after that it will hit the register API let's say this is warning that is because in the register view we need to remove this unused CSRF import now it's done refresh now let's go to register clear this and it hit the CSR of cookie and then here dear Easter button which is working recession Harish Kumar and let's say restored Kumar at example.com then password password and hit delish Tibetan user is registered successfully if you go to database refresh now we have two users now this register method is clean and this API register method will responsible for the CSR of cookie next let's implement this login feature so let's close all this and in the login dot pew first we will implement the login doubt in B laravel F so let's go to laravel app and let's close this let's close this also now here we will say also plug in Logan controller at Logan it's the artisan made controller Logan controller next in D controller login controller calculate method log in and it will accept requests those requests here I'll validate request and it ate here I'll say email that is required and password is also required after that ILM can't log in so you will say if both attempt to arrest [Music] amen and password if a time T successful then it will say return response which is son or user then status is 200 Aoife time please field as I'll - well it is an exception with the message the proprietor credentials incorrect now let's implement this in the new app now here in the login view right here first here a lot data property and it will return home amen and password next we will bind these form fields to the input field here email is the type one model is equal to from dot email and let's go here say V upon model phone dot password yes sir next after on click this login button we will execute logging method so here I'll say at click dot prevent to prevent the default behavior and then execute login method so now let's get this method right here methods loading that third now in this method we will add a login API so let's create blogging API in the API user dot GS here I'll great login method which is a sink and it is going to accept home and then wait for CSR up at cookie after that we will return API dot host login phone it's done now let's import this in the login view so you'll say he is slash loser next Indy no be method you'll say user dot log in and then you pass this dot form now let's see this in the browser if it is working here you flash clear this now if we hit this login button it field see what is the issue in the terminal we forget to run ads and circum on until are of a lab so PHP artisan serve these and hit login button it's working and we get the 422 error that is validation error now let's handle revalidation next-gen say dot catch [Music] and say if error dot response dot status is equal to 422 and then he will say this dot header is equal to add a dot response dot beta dot error next year you need to add feathers property now let's display the add the input fields to say time I will copy the mark-up from the register view taste it yet next and say here added start female and here bastard it's Jen now let's go to browser refresh and this did not work why okay let's take is here he sees errors distort errors here it is also now refresh here and hit the button and it is working after you three successfully logged in you will say dot ten then he'll say local storage dot set item let's say oath is equal to in the local storage we cannot store the boolean value so let's pass the string true after that we will redirect user to the dashboard so we'll say this dot router dot push mean is equal to - hold it son now let's see this next we will say very ish at example.com and password is password T login button now we are successfully logged in and we navigated to dashboard now we have successfully implemented the e login feature next we will implement this logout feature and after that we will handle this dashboard for this log out button we will create logout a play so let's close this so here I will say push out logout and controller is let's say hello gain controller that log out now let's create this login logout method so in the login controller the third log out and you say logout that's done now in the view app let's close this login view register view nandi right here here a letter about methods and say you sing logout and then return API taught post move out and also we will send this see your setup get cookie now in the components navigation dot q here on click this button we will execute the logout method so I will say at clicked or prevent then I'll say flow out now let's create this method so we'll say methods logout next we will need to import user API so they import EPA's user this logo method will say user dot log out der Tann in the login dot view we have said the local storage or true so after local people remove this both from the local storage so here I'll say local storage dot remove item or and then we will redirect to the home page this dot dollar router dot push name is now let's see this in browser refresh now we see the application and in the local storage here we have oath to you now I'm the network let's clear this now if we hit this its NDC a set of cookie and then set the logout button now in the application here it has removed the node from the local storage and user is log out let's see one more time in the login if we use the logs in it is Logan and it helps at the earth true in the local storage now we look out it is navigate to the homepage and both Hobart is removed from the local storage our next implementation is this dashboard this dashboard is only accessible if user is logged in so first here what we will do we will press the logged in user and print its name and its email address right here so in the laravel app we will use this route path it hits this user route and returns the authenticated user and here middleware is Earth API instead of this here we will use this one or centum next indie web these qualities so here what should be the method name let's say earth this earth method will return authenticated user so here I'll say return EP i dot cat and then he'll pass slash user this user tout path is the this one now in the use dashboard view aryl add data property and it will return use it which is initially null next I will use mounted hook this mountain hope will execute immediately when this dashboard component is mountainy into the browser now in this mountain method I'll hit the user API so first let's import the API API is slash user now in this mounted method I'll say user dot forth and then this spawns [Music] next she'll say this dot user is equal to this small short data next we will print this user right here so here I'll say B - f user this diff should only visible if we have this user natural print takes username so it's a user tour name and yes it will say to you dot email now let's see this in the browser refresh now here you can see it has hit the user API but we get the an authentication added refresh again and again here we get the 401 status code that is an authorised error now if we login the login button now we get navigator to the dashboard this time it at the user API but we get D 200 because now we are authenticated here it has authenticated user data we pressure gain if the user a payee and we get the authenticated user move out in the dashboard and here we get unauthorized error click - and here we have unauthorized error now we have implemented the authentication system our next step is right now any user can access this dashboard so our next step is this dashboard should be accessible to only authenticated user so for that we will use before each with view router that is that is this one I will copy it from here and space this right here now we need to modify it so here I'll add meta field or only to this matter will can be anything you want next here I'll say to mash some records if record meta or only and then we will check if user is authenticated so for that here I'll create a function is logged in you'll see a return local storage dot get item authe now next here will say if user is not authenticated then it will redirect to the login page now in the browser this time if we try to hit this dashboard it is not working and let's type a dashboard it is immediately redirected to login page let's say we logged in now we are allowed to the dashboard same thing if we are logged in it it doesn't make sense to to have access to the login page so what we will do if user is logged in then this login and register page is also not accessible so next in the right here in the login method here I will say meta guests only - same thing I'll add right here next I'll copy from here to here and then I'll say else f ll say Gaston D and so if user is logged in it should data to the dashboard now let's see this now if you try to hate the login page it is immediately redirected to the dashboard so this manually and easy to be directed to dashboard same thing if we try to it mr. page we are adapter to the iSport our next step is this login and register links should be visible if user is not logged in and dashboard and logout link should be visible if user is logged in so for that in the navigation component Erol our data property and he put return is logged in and usually these Falls next year the lad mounted property when this navigation component is Mountain it will check for the local storage earth so you'll say this store is logged in is equal to local storage dot get item oh and right here will also say it should be a boolean value when this component is mounted it will check if local storage has earth value and if he has author you will store 2 in this variable next you'll say this login button should be visible we if user is not loaded same thing this mr. button should be only visual if user is not logged in and dashboard button if user is logged in and this login button if user is logged in let's say this now let's see in the browser refresh we can only see - word I know about if you log out PA logged out but it is not reflected immediately login and issue button is not visible here we can only see - foreign local IP refresh and now we can see login and register link and dashboard and logout is not equal same thing if we login and this time we are logged in but we cannot see dashboard and logout button refresh now it is visible so the issue is that this local storage is not reactive so the idle choice is to use VX for days but this video tutorial is not about UX so instead of UX here I will use event bus so in the login page here I will say when user is successfully logged in then I will say this dot dollar root dot dollar limit log in and it will mate Rio next in the navigation here we will say this door dollar root dot dollar on again and then this dot is low gain is equal to you and after log out you know say this store is logged in is equal to false right now we can see the dashboard and logout button now let's log out immediately we can see login and register button and now let's login and we can see - one and logout it's working now we have implemented the full authentication system but here I am still not done yet I want to show you one more thing now let's see the rest of you here on click this register button we add this register method and it has executed this user register EP I go in the user history API every time we hate this list user register a pipe it will hit this get cooking API so do we need to hit this CSRF api every time we do when we hit this restore API let's see this let's log out and in division here we hit the rest Overton it has executed a CSR of cookie and what the CSR Pookie does if you see the header here it set the cookie CSRF token and laravel session and in the application right here in the cookies here here we have this laravel session cookie and CSRF token so now if i comment this and save it now this time refresh it now this time if I hit this register button this time it has not hit CSRF API but we get the correct it means it worked without hitting this csr of cookie every time but if I removed both these cookies now this time we will get 419 error that is token mismatch added because we have removed the token less enable this and refresh now it worked we get the csro cookie and it has hit the register a pipe that give us the validation error and in the cookies it helps at the laravel session and token cookies so we don't need to hit this CSRF API every time we can skip this if we have already this token so what we can do we will check if we have this cookie already then we can skip this API and immediately hit this register a plane it will improve the performance of the app so let's implement this for that for that I will add a additional package to handle cookies that is npm install' GS cookie now it is installed next in the CSR after GS Erol import cookie from GS - cookie nets in this method here I'll say let token is equal to cookie dot cat in the application this one and next I will say if we have token then we will return because this returns a promise so here I will also return a promise new promise and it will have the soul it is so that's all we need here here in determined less Randy NPM let's go to the browser refresh on the application we clear this and in the network you can notice first it has at the CSR of API and then register API and the application this token is set so now it will not hit the CSR of API only the recipient know list as the entire application if everything is working the same name is John Doe John at example.com password is password confirm password and register now we navigator to login page on the slogan the user John at example.com and password is password and we are logged in everything is working if we try to wait the login page it will not work immediately redirected to - put the slope of the user and try to hit the dashboard didn't usually detector to login page now we have successfully implemented the login and registration feature using the laravel center package in DB web in the next video we will convert this authentication system into the API token authentication so thanks for watching if you liked the video hit the like button share this video and don't forget to subscribe us see you in the next lesson [Music]
Info
Channel: QiroLab
Views: 45,545
Rating: undefined out of 5
Keywords: Laravel Sanctum, Laravel Sanctum Register and login, Laravel Sanctum Authentication, Sanctum SPA Authentication, laravel airlock, laravel airlock vue, laravel airlock auth, laravel spa auth, vue spa auth, vue single page app, laravel single page app, laravel cors, laravel 7, laravel 7 whats new, laravel 7 new, laravel package, laravel sanctum, laravel airlock renamed, qirolab, learn with qirolab, laravel 8, laravel8
Id: 8Uwn5M6WTe0
Channel Id: undefined
Length: 53min 31sec (3211 seconds)
Published: Sun Mar 29 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.