Authentication in Vue using Laravel Sanctum

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Hey everyone, I'm back with another tutorial! I've been keeping an eye on this package every since Taylor dropped it earlier this year. A project I took on recently had me dive into it, and it's been an absolutely dream to work with. Much better than jwt-auth in my opinion.

This video takes a quick surface-level approach into getting a simple dummy backend set up with Laravel, a Vue component mounted to a Blade template, and then how to make authenticated API calls between the two.

Let me know what you think!

👍︎︎ 2 👤︎︎ u/aschmelyun 📅︎︎ May 07 2020 🗫︎ replies

I've been using https://github.com/tymondesigns/jwt-auth for years now in combination with https://github.com/websanova/vue-auth, and it works perfectly for all my use-cases... I was wondering if you could tell me of any benefits to using Sanctum over jwt-auth ?

👍︎︎ 2 👤︎︎ u/spar_x 📅︎︎ May 07 2020 🗫︎ replies

Saved for later :)

👍︎︎ 1 👤︎︎ u/adampatterson 📅︎︎ May 07 2020 🗫︎ replies

How is making a get request to fetch the csrf-cookie that is not already in the page still secure? Real question out of actually not knowing.

👍︎︎ 1 👤︎︎ u/BreakParadigm 📅︎︎ Sep 26 2020 🗫︎ replies
Captions
hey everyone Andrew here if you haven't heard about it yet laravel sanctum formerly larval airlock is an incredibly streamlined official larval package that offers a featherweight authentication system for single page applications mobile apps and token-based api's i made a video last year the featured using JW TS to authenticate a view app with a larval api while this package might not replace time ins established JWT off entirely if you're going to use laravel version 7 or higher is a much better choice installation and setup is a breeze and in this video i'll show you how to go from a blank laravel project to a view powered component making authenticated calls to a back-end API here we have a brand-new out-of-the-box larval project the first thing that I want to do is set up our API for this simple demonstration its purpose is to get back secrets attached to a specific user we can get started on that by creating our secret model with artisan you'll notice throughout this video that I'm using DCR instead of PHP in my command line my local setup is running through a docker network and my alias for docker compose run is set to DCR if you'd like to learn more about that i've linked my larval docker video below i'm also adding in the migration flag so we can create our migration for our secret model at the same time let's open up that migration file and create the columns that our model needs for a secret I think all that should be required is the user ID to attach it to a user and then a text column for the actual secret looks good let's save that and run the migration alright that went through well let's open up the model and make some necessary additions first protected guarded set to an empty array I just want to be able to autofill any columns of data for this model second the user relationship all secrets will belong to a user and so we'll return this belongs to app user now we just need to perform the inverse on our user model at the bottom we'll add in a secrets function that returns this has many app secret we're going to need some test data to make sure that our app is working properly while we could go into the database or artisans tinker shell and create a few dummy models there I think using a factory would be easier here our laravel app already comes with a factory pre-configured for our user model so all we need to do is create one for our secrets artisan makes us easy with the make factory command and using our model name with the convention we'll just call it secret factory passing in secret as our model argument also sets up a lot of the boilerplate for us let's open up our new factory our model has two data points that we need to create when this runs a user ID which we'll just set to one and a secret for that we can use fakers text element which will generate a nonsense string you might be wondering here why we're hard coding a single user in when we could have more than one well I'll show you how to override specific attributes when we're using factories here shortly so that we can specify other user IDs if needed let's save that factory file and open up artisan tinker in our terminal we can create a user by using the global factory method provided by laravel passing through our model and calling make there's a problem though that user isn't saved in our database it was created as an eloquent object but it wasn't stored persistently that's kind of intentional though since factories are usually used during test runs and you wouldn't want your database populated each time that you ran an automated test we can fix this by replacing the make method at the end with create this will generate the user object and then save it to our database afterwards let's go ahead and create two secrets as well using the secret Factory you'll see our hard-coded user ID as one in here and we'll create another set of two secrets but this time for the second user we made this is where I'll show you how to override those defaults that we set in our secret Factory all you have to do is pass in an array of overrides to the create method at the end of the factory call so we'll override the user ID with a value of two we now have two randomly generated users with two secrets each the next step that we need to tackle is creating an API endpoint to get our secrets opening up our routes API file will remove the default route and comments in there and add in a single new route route get secrets and it'll use secret controllers index method let's save this and generate our secret controller using artisan okay opening it up we need to add our secret model import statement and index method in here for now let's just return all of the secrets in the database going over to our browser and navigating to API secrets we can see our four secrets showing up just as expected I think we're in a good place with our dummy API so let's start working toward actually being able to authenticate a user into it this is where laravel sanctum comes in in order to get started we'll have to require the laravel sanctum package using composer and then publish the configuration file and migrations using artisan vendor publish there's honestly not much in the configuration file and there's nothing in here that we'll have to adjust for this demonstration finally we'll run artisan migrate to generate those new tables into our database okay going through the documentation will be using sanctum to authenticate an SBA according to this we'll need to add in its middleware to our API group and app HTTP colonel above the throttle call will add in the insurer front end request our stateful class that seems to be all we need for the API side of things so it looks like it's time to shift our focus toward the front-end laravel comes with a default welcome blade template that's displayed on the root path and we'll copy this to a new file called app blade PHP in our routes web file let's change the Welcome view to our newly created app view going back to our browser it looks like that's pulling in the correct view laravel 7 also introduced a separation of the front end compared to previous versions if you want a view or authentication boilerplate you'll have to install a separate package the documentation lays everything out and so all we need to do is follow a few steps first let's require the larval UI package using composer and after that's done installing we can generate user login and registration scaffolding as well as some boilerplate front-end code using one of the few artisan commands since we're using view in this demo let's run artisan UI view auth to finish up this front and install we'll have to install the NPM dependencies and run a dev build on the bootstrapped assets opening up our app.js file we can see that view has been added as well as an example component the app s CSS file that was generated contains a google font as well as the entire bootstrap framework let's navigate back to our app table blade file and get rid of all this hard-coded CSS we'll add in our stylesheet instead using the mix helper our body content can also go except for this wrapper div which we'll use for view this will be our front-end apps mount point adding in a call to our fjs script using the mix helper and the provided example component completes our changes let's see if everything's working yep on our browser we can see the example component and it's confirmed using view dev tools now that we verified everything is installed and been set up correctly let's work towards displaying our secrets we can copy over this example component to one called secret component we're going to need a login form and a list of the secrets that are returned to us our data object will hold a single value for now the array of Secrets to display to the user in apt is let's register this component under our example component and change the component displayed on our app blade view instead of running NPM run dev each time that we make a change to the app KS file or any component we can use NPM run watch this starts a script which watches for any changes made to our s CSS javascript or view files and recompiles everything after saving okay let's start scaffolding out this secret component the first thing to tackle is the login form since we're not submitting this form through the browser our action is just blank and instead we'll be using views submit prevent Handler calling a function called handle login which will create shortly to send the user's info to our API this form should be incredibly basic as all we'll need is an email address a password and a button to handle the form submission alright that's looking good could be spaced out a little more okay that's better let's add in a title as well okay so we can use this form but nothing is going to happen the form submission is calling our handle login method but there's nothing there for it to do time to add some functionality first we'll need to create a way to store the entered in username and password you can use two separate data points for this but I prefer using a single object called form data we can test this out and see that as we change the email and password our component is storing that in the form data object if we head back over to the larval sanctum documentation there's a whole section on getting started with SBA authentication so let's follow that real quick and see what we need to do this Axios defaults with credentials flag needs to be set to true so we can head into our bootstrap j/s file and add that below the other Axios defaults call then it looks like before we make any calls to our API we need to make a get request to this Sanctum CSRF cookie endpoint which will set CSRF protection and allow subsequent requests uninterrupted we'll add this call to our handle login method in our secret component and just console.log the result for now so we can keep track of what's going on okay so if we attempt to sign in we get a single response back which was that call to the CSRF cookie endpoint if we open up our dev tools application tab and navigate to the cookies section we can see that a couple of cookies were automatically set on our front-end an xsrf token which handles the CSRF protection and a laravel underscore session token that second one is super important after we authenticate into a larval app it's what will determine our authenticated status when we make calls to our apps API let's continue with the actual login since we use the auth scaffolding when setting up our front end there's a login route exposed that we can call to automatically attempt our users login so after our CSRF protection route has resolved we'll make a post request to the login route passing in our form data object that contains the entered an email and password just like the last time we'll console.log there is it's back to determine what's going on so now let's try to log in oh we get an error ah because this wasn't one of the users created when we ran our factories let's grab an actual email from one of those users in our database okay let's try logging in again perfect no errors and a response back it might not look like it but our laravel session cookie has been updated and allows us to make subsequent calls to our larval api as a logged in user let's test this out by getting some secrets we'll add a method called great of Lee get secrets it'll call our API endpoint from earlier API secrets and return back the response in the console let's log in with our dummy user and we can see our app secrets appearing in the console just as expected now might be a good time to actually display those back to our user let's create a simple list of secrets using views v4 loop will display back to the user the date that the secret was created as well as the secret itself that should be good enough we're also going to hide the secret to div until their secrets present and hi the user login form once those secrets have been retrieved finally we'll replace the components secrets array with what gets retrieved from the API call let's test it out beautiful after logging and successfully the form is hidden and a list of the app secrets are shown on the screen but there's a problem we don't want to see all of the secrets right we just want to see those secrets attached to the user who's logged in using larvell sanctum and that larval session cookie that i mentioned earlier makes this super easy and I'll show you how first let's open up our secret controller again and we're going to add a request object argument called request to our index method then instead of returning all the secrets we can call request user which will get the authenticated user and then tack on the secrets relationship to return all of the secret models associated with that user save this and let's test it out one more time perfect we see just those two secrets that were attached to our authenticated user so what about subsequent API requests well you need to make a request to the login endpoint each time nope and that's the beauty of this package once those cookies are set after calling the CSRF cookie and login routes as long as you don't refresh the page you'll be able to make as many additional calls to the larval api as you want I made this quick button here as an example for that it calls the get secrets method directly and if we log in and open up the console each time that I click it it's returning back the secrets data attached to our user those calls are automatically adding in the larval session cookie in the requests headers and laravel is decoding that to determine which user is authenticated if any just like what would happen on a traditional PHP web app this means that you can make subsequent and recurring API calls that require authentication throughout your entire single page app as long as you've signed the user in beforehand well so what happens if we get rid of these cookies and try to make a request it fails with a 500 error property secrets of non object that's because in our secret controller requests user is returning null right now there's no user authenticated into our app because that laravel session cookie is invalid or doesn't exist we can check for this by adding a simple conditional and overriding it with a custom response or message let's just say that the user doesn't exist there we go our custom error message displayed if a user isn't signed in and that's pretty much it I've only just scratched the surface of what this incredibly powerful yet simple package does but I hope you've learned something from it this will help you get started on authenticating and s.p.a with laravel using sessions and a stateful front-end but there's plenty more you can do with sanctum such as token-based authentication and protecting routes with middleware huge thanks to my patreon subscribers and all of my supporters as always if you have any questions please feel free to reach out to me in the comments or on my Twitter linked below thanks for watching you
Info
Channel: Andrew Schmelyun
Views: 41,300
Rating: 4.8937583 out of 5
Keywords: laravel, vue, vue.js, web development, laravel tutorials, web dev tutorials, php
Id: eeMtmkDZ72Q
Channel Id: undefined
Length: 23min 6sec (1386 seconds)
Published: Wed May 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.