Securing a Laravel API in 20 minutes with JWTs

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone today we're going to learn how to secure and authenticate a laravel API using Jada BTS and specifically this JWT auth package from Taemin what RJ to BTS they're essentially an encrypted encoded string that represents a JSON object and is used for authorization and validation of information coming from two different parties usually a client like a web browser and a server so the web authentication portion of this that we're going to be using jdb T's are passed in through the authorization header using the prefix bearer with a colon in order to determine that the person that's coming from this application is who they say they are let's get started I have created a boilerplate larvell 5.7 app that allows a person to sign in it shows posts that are kept to their account and allows them to create store and update posts connected to their user ID using this simple format now this is good for a web app where your larval insulation is hosted on the same place that your views are let's say we want to use the functionality of these posts on something like a mobile app or a single pageview application hosted on a completely different website we want to be able to communicate between those clients and this API we want someone to be able to log in and see the posts that are connected to their account by default we can install the larval Passport but I feel like in this case it's a bit much the JWT auth package in my opinion is slimmer it's faster to get set up when we want authentication just from an email address and a password this provides the same level of security with a much easier barrier for entry so let's get started if we go into the source code for this app that I have set up now and we go to our routes web file you could see I have the posts routes wrapped underneath our off middleware which is currently running on the web driver using session tokens you want to be able to authenticate somebody without session tokens you wanna be able to authenticate them with a JWT if we go back to our API file I have a single API we're out set up right now called posts and if we open up postman's we can see that this route returns back all the posts in the database currently there is no way to just get back the posts that are associated with a person who is logged in we could modify this to get posts that are associated with a particular user if we wanted to have a public API that would allow anybody to view anybody's posts but for something like a social media site or a notetaking application we don't want that to be the case you know we don't want to view anybody's notes that are out there so this is where the authentication that we need it comes into play we need to be able to determine who is it that it's coming from this client and we need to get their information and return it back to them so let's get started by installing the JDBC off package by requiring it in composer and I'm specifying the version name here because as of the date of this video there are two versions one is stable at five point three but Taemin is releasing the newest version 1.0 fairly soon it's in release candidates right now so this is the version that we're going to be using and we'll let that install alright once that's installed the package has been discovered successfully because I am on laravel version 5.7 if you are using laravel 5.4 or below you'll have to manually add in the service provider into this service providers array you can view the service provider that you need to add by going to the documentation for this package that I've linked in the video description below alright now that our package has been installed and discovered we can move on to publishing the config file for it using artisans then there public command we won number eight and it copies over the config file to config slash to be T dot PHP and if we open that up we'll see that we have a bunch of different configuration options and most of them are set in our dot env file the only thing I'm going to focus on changing is this JDBC underscore TTL which is the time that the tokens are valid for in minutes by default at 60 or an hour I'm going to change out to 24 hours and so if I go into my interview file I can add in a DB tennis-wear ppl equals 1440 save that and the last step before getting started integrating this package with our API is that we need to generate the secret use during the encryption of these JWT s and JDBC auth package provides an artisan command to easily do that JWT secret that that's all set we can get started integrating this into our user model in order to do that let's open up our user dot PHP file and we need to add in the JWT subject contract and allow it to be implemented by this user model the only additional step is adding in a GUID JDBC identifier method that returns the key and a JWT custom claims that so now is just going to return a blank array our user is all set up to be authenticated now we need to have our API have a middleware that understands JWT s and can use them so if we open up our config auth file you'll see that we have two guards a web and an API guard driver for the API guard currently is token we just need to change that to JWT save exit we can finally get started in building routes that will authenticate users through the JWT auth package now in my app I already have methods for authenticating users coming from the web dashboard I need a separate controller thought that akkadian users with the JDBC off package let's get started by adding in our controller we're just going to have a single method called login now skipping back a little bit on this config auth file now we change the API driver to JWT these are under guards now by default the guard is wet that's used on our earth middle where we had change the default to API it would easily allow us to use this entire application with JWT anything that's wrapped under the auth middleware with you GWT but I don't want that because I want to keep this web dashboard and also use this API we need to be able to separate what controllers and what routes we want to be under the GWT off and what routes we want to be under the traditional web off but be able to use la Ravel's off methods in both in order to do that I'm going to show you a quick little workaround that'll allow us to do just that so what we're going to do is this main controller that's under app controllers we're going to copy that and use it in our API namespace and we are going to add a construct method that'll set the auth driver as API so what this does is that any controller that extends this controller is going to use the JDBC authentication so back in our logging controller we are going to use the controller that we modified and on our login function and our login function we're going to grab the users credentials we only want the email and password we're going to use that to generate hopefully a token using off attempts and then return that's okay now let's open up postman and let's see what happens when we post to the login controller our email and password and look at that we get a token back now I actually want this to be JSON response so it just looks a little bit more tidier additionally we want to add in an error method that will alert us if the user gave back the wrong credentials because right now let's see what happens if we add in the wrong password it just says token false not really that helpful comment that out and we'll do [Music] all right that way if the token doesn't get generated will return a response it just says incorrect email password with the correct 401 header that can be used to catch errors on our client side but if we provide the correct email on password we get our token let's use this token to get posts that are associated with the Jane at email comm account let's open up our post controller so first let's create a route we'll call it post self and we'll create this method in our post controller before we continue we also have to use our modified API controller ok now that that's done we need to grab the posts and we can easily do that using the auth user method and excusing the relational model grab their posts and then we can return those if we go back to postman and we get these posts without adding in this token let's see what happens first it kicks back an error now the reason for this is that when we're using this alt user method here if a tokens not provided or tokens incorrect it returns null and so in order to combat that we can implement a try-catch method so we'll try to get the user using a user or fail a method provided by the JDBC all package and that doesn't occur we'll add this user not defined exception and will this return all right now let's see what happens when we send that request we get a response that says an error has occurred so let's log back in and get our token we have our email address and correct password we get our token here copy it and then we want to get post self get go-to authorization bear token paste send we get our posts okay what else can we do with this let's create a method that creates a new post and we'll get just what we need which is the title and the content for our posts and we will create a new post after finding our user using this try-catch method so use your coats great details and we will return the post that it's created so we go back to postman and we will add in title this new post content isn't as cool we're not passing the email password oh we forgot to tie this to a routes open up our API PHP file okay back to postman posts create posts we have our authorization token we have our title and content send it we get back the post title content user ID and ID now if we go back and we get posts self we see our posts attach to our account now this try-catch method that we're adding into each of these methods it's definitely redundant so we can actually move this and we will put it in the control that we created called a user and what we'll do is return this user from this method so that way on any of these controllers that extend this API controller we can call user as this user now what happens when your token expires it's no longer valid very easy with JDBC auth if we add in a new route to our API dot PHP file calls refresh we'll just use this standard we'll just use the same login control that we had and we're going to generate a new token using the OO refresh method and we'll just return that as a JSON response the same as the method above now what happens when we call this method let's find out so in postman we will call API refresh and we get a new token when that refresh occurred it has invalidated our current token the token that we're using right now is no longer valid and should be replaced by this new one now let's see what happens if we call the same method using our expired token the token has been blacklisted we should be checking to make sure the token is authentic first giving us the chance to return an error and so let's add in a try-catch method now okay so now if we go back to postman and we send for the refresh we get this error the token has been blacklisted JSON response which is what we want with the correct 401 unauthorized status maybe a 422 might be better but regardless that's about it we have successfully authenticated and secured a laravel api we have learned how to create JW TS use them in our API calls to associate a particular user with request to the server and get back information associated with that user and we have learned how to refresh tokens before their expiration date if you have any questions at all about this or anything else related to laravel or JW TS please feel free to let me know in the comments or you can find me on twitter at h million thanks for watching
Info
Channel: Andrew Schmelyun
Views: 58,967
Rating: undefined out of 5
Keywords: laravel, web development, php development, coding tutorials, asmr, mechanical keyboard, full-stack
Id: 6eX9Pj-GhZs
Channel Id: undefined
Length: 20min 35sec (1235 seconds)
Published: Sun Dec 09 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.