Getting started with Laravel Fortify and Sanctum

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone andrew here this is part two of my three-part series on laravel authentication in this video we're going to be discussing two packages fortify and sanctum let's dive right in first with fortify we have this test application set up already as you can see and it has a dashboard route now the problem is that this route should only be accessible by me someone who's logged into the application this shouldn't be available to the public so we need to add in a middleware guard to protect this route from unauthenticated users if we head into our applications code we can tack on this middleware method to the route get request passing in off and now if we go back to our browser and refresh we are met with an error that the login route isn't defined this is because that middleware is trying to redirect us to a login screen since we are currently not authenticated into the app we could go back into the routes web file and add in a login route or we could use fordify taking a look at the documentation for it fordify is branded as a front-end agnostic authentication backend implementation for laravel essentially fortify handles the routing and controllers necessary for all authentication actions but doesn't include any front-end code because of that most of the time you'll probably not use fortify on its own instead something like breeze which implements fortify but with styled frontend components might be more applicable but anyway let's see how this works heading back to our code base let's open up a terminal and run composer require laravel fordify after that finishes up artisan vendor publish with the fortify service provider and finally artisan migrate to pull in the database changes so now if we go back to the dashboard route that we were testing with earlier and refresh we are seeing a different error login view response is not instantiable this is a direct cause with how fortify operates because there is no front end included you have to not only create the markup and styles for it but also initialize it in your application's code for each all throughout in order to do that first we'll need to open up our config app.php file and scroll down to the providers array adding in this fortify service provider class at the bottom of the application service providers then open up the app service provider class and in the boot method use fordify login view and pass in a closure that returns the view we want to display for logging a user in in this case we'll just call it auth.login the last thing that we have to do is create that actual view i'm going to spare you the boring details and paste in a pre-made template that's built from the breeze package as you can see we have a form that's pasting to the login route this route was automatically added in and registered when we installed the fortify package we also have fields for our email and password as well as a button to submit the form all pretty standard now if we refresh that page we see our form so let's try and log in well we're presented with an error which is good because we don't have any users currently registered in our application but see fortify did all of the behind the scenes work for us all we did was build out a view and it handled the form submission input validation authentication checks and errors that were returned back let's see what happens if we try to visit the registration route we are met with a similar error that we got earlier register view response is not instantiable just like before in our app service provider class we'll call fortify register view and in the closure function return view author register let's create that blade file and paste in our markup just like the login route this pulls styles and layout from laravel breeze we are posting this form to the register route and we have inputs for a name email address password and password confirmation let's go back to our browser refresh and see what that looks like perfect let's give this a test uh oh i didn't type in the same password twice again fortify is handling all of the back end for us all we did was just create a single view okay our user is registered and we were automatically authenticated into our application since we can see our regarded dashboard route now if we try to go back to the login view it should redirect us to a home route but we want users who are logged in to go to the dashboard that's a simple fix let's just open up the route service provider class and swap out this home constant value to slash dashboard now if we try to visit that login route we are directed to our dashboard view what about logging out with fordify well if we were to try to visit the log out route we are met with an error that a get request isn't supported for it by default logout requests in fortify expect posts that's pretty simple to implement though so let's just pull up the dashboard blade template and add it in form action route logout method post and we'll just add a button that says sign out refreshing our browser let's test that out perfect we are brought back to our landing page just as expected also now that we added a login and registered route with fordify links to both of those are available in the top right corner and we can use the login route to sign back in with the user that we registered earlier well that's about it for fordify in the interest of time i'm not going to go to further in depth in this video but the package provides access to password resets email verification and even two-factor authentication all you have to do is register the appropriate views with your application and provide some blade templates fortify's back-end handles the rest let's switch gears now and move on to larval sanctum swapping out the default welcome view for an app view that i've created this is what our example application looks like it's a view component that lets you pull in and display a list of blog entries each with a title and some text checking out the source code for it we have a div here that's looped over each entry and a button that fires a get entries method to grab them a simple api request is what's used with axios and the entries data object is replaced by the response data that endpoint is registered here in routes api all it currently does though is return back all of the entry models in the database but there's a problem with this if we open up the network tab and view the call that's being made to the entries endpoint the data returned contains a user id each entry is associated with a particular user what i would like to do instead is be able to tailor this endpoint to a user who's logged in i don't want just everyone to be able to see everybody else's posts just those for a user who has logged into our app and that's where sanctum comes in born as a kind of alternative to the popular jwt auth package it's a featherweight authentication system for single page applications mobile apps and token based apis essentially it's a two in one package that lets you authenticate spas and their api calls with session cookies or your application endpoints through bearer tokens we're going to give examples of both but to start off with we'll be using the spa authentication first things first actually installing the package opening up a terminal window we'll run composer require larval sanctum once that's done publish our vendor files and then artisan migrate to add some database changes next we'll need to add this ensure frontend requests are stateful middleware to the api middleware group this as its name implies allows api requests coming from our spa to contain session cookies that automatically authenticate and validate requests to our back end opening backup our view component we'll have to make some adjustments in order to accomplish what we want first in our data object we'll add a user attribute that's null by default and a login object containing an email and a password this will store the values for the form that our user will sign in with speaking of signing in let's create a method called handle login next it'll use axios to post a request to the login route with our form data and if that's successful make a get request to the api user endpoint and use that data to replace our null user data object heading into the routes api file we can adjust the middleware for that user route from off api to auth sanctum using the created lifecycle method from view we'll need to make a get request to the sanctum csrf cookie route before any other api calls are made this sets the csrf token as a session cookie protecting and allowing subsequent calls to our application endpoints to take place now let's create that login form first we'll wrap our current entries list in a div that's only displayed if the user data object is available and if it's not we'll display a login form containing email and password inputs setting the v model attribute on both of those to the login data object properties and a button at the bottom fires off the handle login method that we created earlier let's head back to our application in the browser refresh and test out what we've created so far okay let's add in our user's email and password and click sign in uh oh we are getting an error back in the console the login route is returning a 404 that's expected though we haven't created one in our application if we open up our routes web file we could add a route get request to login but we could also just use the fordify package that we just learned about installing it through composer publishing the vendor files running the migrations and adding the provider to our config app file we now have authentication routes ready to go since we're doing everything through api requests we don't need any front-end views tied to fortify so let's open up its config file and scroll down to where it says views setting that value to false before we go back and try again let's make a quick adjustment to our component let's split out this api user call into its own method called get user and we're also going to call this during the created method after this csrf cookie request has been resolved this will ensure that our application responds properly if a user has already logged in and their session is still active even after the page has been refreshed we also need to go into the resources js bootstrap.js file generated by laravel to add in the following line window.axios.defaults.with credentials equals true this tells axios the package that we're using to make api calls to send the authentication session cookies in all requests automatically and then in the route service provider class we'll swap out the api middleware in our api routes to the web middleware so that session cookies are used throughout it let's head back to the browser and sign in with our test user all right perfect we got our user and we're seeing the welcome screen instead of the login form we can see the user data that was passed back to us through the api in the network tab hitting get my entries displays a list of entries but it does the exact same thing that it did earlier showing all of them not just the ones associated with my logged in user no worries though that's a pretty simple fix heading into the routes api file we can change the return for all entries to use request user entries this returns the entries for the currently authenticated user and this should use the auth sanctum middleware as well so it's protected from unauthenticated users now if we refresh we won't have to log in since our session cookie is still valid and clicking get my entries displays just the entries associated with our user which has an id of 1. so that's authenticating and making calls with the spa side of sanctum what about tokens let's go into our view component and create a new method called get token it's going to make a post request to api tokens create passing in a token name attribute that i'm just going to hard code in as my token when resolved we're going to set a token data attribute to the response data token item returned back let's set that token item as blank in the data object for now and add a second button under our get my entries button to fire off that new method we'll also need somewhere to display that token so an input with a disabled attribute here should work nicely v model equals token and perfect now we just need to create that api route it calls in routes api route post tokens create and inside the closure function for it token equals request user our authenticated user create token passing in that token name that we hard coded into the view component we'll be returning the token generated as part of an array with a token attribute just like our entries route this is also protected with the auth sanctum middleware so unauthenticated users can't access it finally we'll need to open up our user model and add in this has api tokens trait to enable tokens to be used and generated for this particular model let's go back to our browser refresh and test this out we are still signed in clicking get my entries works as expected and if we click get a token our input is filled with a token generated by sanctum we can test this out by using a program like postman a new get request to our test domains api entries endpoint and if we don't include anything in the headers we are met with an unauthenticated message and a 401 unauthorized response code but if we include the bearer token in the call we get back a list of our users entries just like in our application if we clear the session data for our site we can test the login again and everything is working just as expected that's about it for this video you've learned how to install setup and use laravel fordify and sanctum authentication packages you've learned how to create views for fortify use spa authentication with sanctum and generate access tokens for api endpoints used by external applications huge thanks to my github sponsors and everybody else who continues to support these videos as always if you have any questions about this or any other web development topics please feel free to reach out to me in the comments or on my twitter linked below thanks for watching
Info
Channel: Andrew Schmelyun
Views: 6,538
Rating: 4.958549 out of 5
Keywords: laravel, fortify, sanctum, php, web dev, web development, web dev tutorials, laravel tutorials, php authentication
Id: W7owQcBYerA
Channel Id: undefined
Length: 19min 34sec (1174 seconds)
Published: Mon Mar 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.