Laravel API Authentication using JWT Tokens

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this tutorial we'll build an authentication system using laravel sanctum before jumping to the code i would like to remind you that this video is meant to be combined with other videos so if you like to combine laravel with angular react nexjs view not js orsvelt i'll provide a link in the description and you can pick your favorite there those videos are already or will be uploaded on youtube also make sure to check scalablescripts.com so let's install the packages that we will need first we need to install composer go to getcomposer.org click download here and you will see here the installation instruction for composer so copy these lines to your terminal and you will install composer second you need mysql so go to dev.mysql.com downloads here you need to install the mysql community server and also mysql workbench to see the data in the database and now let's go to laravel go to laravel.com click documentation and we will click here installation via composer so this is the command that we will use i'll copy it and i will open my terminal i'll paste it and i will change the example up to laravel auth so now my laravel project is being created let's wait till it's completed so the project is created now let's go to the folder and run php artisan serve so now our server is running on this port so i will copy this url and open a new tab now this is our project which is installed and now i will open with my ide my id is phpstorm so it is good for php development if you don't have it because it's a paid software you can use visual studio code so it is the same now what i will do is create our first route and the first controller so the controllers are created inside up http controllers we have an example controller here which we won't be using and to create a controller we need to run the command php artisan make controller i will call it auth controller so automatically we can see the controller is created for us here i will create a function i'll call it user and for the moment i will return authenticated user here which is not authenticated but to show you how to return a simple route now let's go to the routes so we want to return this to our browser so go to api here i will delete this because we don't need it and to other out we have to use it like this route we need the method in our case that will be a gas met get method the endpoint is user and we need to call now this function in this house controller to do it we have to put here an array where the first parameter is the house controller itself uh quad quad class so here we are mapping as a string the path to this file and the second parameter is the method in our case is user so we are mapping the out controller and the user method and we are done so now we can see this authenticated user in our browser but first i will stop my terminal here and i will use the terminal from my php storm so php artisan serve this is uh nothing so it's the same and our end point now i will close this other tabs will be not users this is not found but api slash users i made a mistake it should be user so we get the message authenticated user so as we can see we got our first endpoint now let's connect with the database so first i'll add the database here mysql my credentials for my local mysql are the user is root the password is root root and i will create a database called youtube laravel out so we successfully connected and now we have our schema which is empty and let's connect to the schema let's go to our emv file and here we have the mysql credentials so our database is youtube laravel auth username is root and password is root route so we added the necessary configuration and now we need to create some tables in the database and we will do it through migrations so go to the folder database migrations and we have some migration predefined one is the users table which we will be using but i will make some changes and the other two migrations one is to rest the password we won't be using it in this tutorial so i will delete this file in the create field jobs table we don't need them both we need just the create users table here we have the name the email email verify that we don't need it we need the password and we can use also the time steps so this is our user let's keep it very simple now let's run the migration so here is a server we don't have to touch the server open a new tab and run php artisan migrate to run the migrations and we run one migration now if we open the database we will see that we have two tables one is the migrations table which stores all the migrations that are run and the other one is the users table that we just created so these are the fields that we added and these are the timestamps the timestamps we can see them so this is a timestamp now let's go to the user model because we made some changes i will remove here the remember token fielable properties are properties that we need to create so we need to set ourselves in order to create the user so right now these are okay the hidden value is okay email verify that we can remove it so our user looks completed now what is left is to create some users so in the house controller now i will add another function register so now let's try to register one user this will have a parameter here which is the request so we will be using a post request and we will send some data to register the user and those data will be stored in the request now to create a user so the user variable is equal to user so the model that we just created create and here we will pass the data that we need so before i add the data to use a class make sure to import it my ide automatically helps me which it imports the name space automatically if yours doesn't make sure to add this namespace we will call a function create and inside we'll put the data that we need so we need the name and to get the name from the request is request input name we need the email so we'll get it request input email also and the third parameter is the password so all these parameters are the fillable parameters we can send the password like this we can set the password sorry but we don't want to store the password as it is because we have to hash it password should should be stored hushed so fortunately we have a function which is hash from illuminate support vacates hash and to make the password so to hash the password we have to call make and we have to put this request input inside so that's it our register user we have to return it the user that we just created so i can remove this variable because it doesn't make sense to have an extra variable so i will just return here directly the user that we just created so to keep everything shorter and cleaner and now let's create this user first we have to add it to the routes also so we have this route i'll duplicate this and now this will be register but the method is different instead of get will post so we'll post to the register route and to the register function so this is our new endpoint now we have to test it to test it we have to install a new software called postman so make sure to download and install postman because we cannot test it anymore to the browser i'll copy the end point here and let's make a request to api slash register this is a post request and we will send some data row here select and we will send some json so we need the name a email at a.com and the password a so this is the data that we'll send let's try to send it and what we can see is the created user because we have some extra values like the updated that created that and also the id also if we open the database we'll see this user is created the password is also hashed so we don't know what password it is and because it's hidden here we don't return the password in the response so now we got one user now we need to login with this user so i'll add another function here login before i write any code here we need to install another package called laravel sanctum so this is a package that helps us authenticate and makes it very easy to authenticate via apis so let's copy this command open the terminal and here install laravel sanctum we have some instructions here so we can publish the provider publishing the provider means that if we go here to the providers we will get a new provider sorry my bed it's not here but it's in config so here we have a sanctum.php file so when we publish providers usually means adding files in the config file so here we don't have to change anything so everything is correct but we added some migrations do we see the migrations here i don't think so we can see personal access tokens table so we added also a migration and we need to run php artisan migrate again to add this table so what is this table this will store all the authentications of the users when the user is authenticated a record will be added here and you don't have to know how this works because laravel sanctum will take care of that so we migrate it this is a middleware which we don't want to add for the moment so we we will use a single page application so we don't need this do we need something else we don't need also this we need to add his api tokens to the user so go to the user and here we will add a new trade has api tokens from laravel sanctum also make sure to use the namespace here so s api tokens this is the namespace so with this base it basically tells us that this user can be authenticated using sanctum now and that's it basically now let's try to login so here to login we have a class called auth from illuminate support facades out and we have some functions and the function that we want to use is attempt this function will use our email and the password and trying to login our user first let's get the request also here and inside the request we will have the email and the password so we can do it like this so we can set the email and this time the password we don't need to hash it this is perfectly fine but i prefer a easier method which is request request only email and password so the result will be the same but it is one line so it it is cleaner i'll wrap this with an if condition so this can return either true or false if returns true it means we successfully authenticated but i will add the exclamation point here so if it is unsuccessful will return response that will say message invalid credentials so this will stop here so if we go if we write code here it means that we are authenticated if we return here it means we don't go here on line 29 we stop here so we return the message but we have to return also the status code because we when we return just message means everything worked successfully but this is not the case we didn't log in and we can return the numbers like 401 which is unauthorized but i prefer using some constants so it's response from symphony component http foundation we need to import this namespace and the status code that we want is http unauthorized so this makes us makes it easy to know what status we have to return this is the case when the user is not authorized now let's get the user when is authorized the user right now is equal to auth user and let's return it for the moment and let's see if this works so open postman i'll copy this endpoint paste it here and this is login we need to send a post request and the data that we want to send is at a.com sorry email a a.com and the password is just a let's see if we return the user so first i will put a different password here we should return invalid credentials so i forgot to add the login my bad let's go to the routes i'll duplicate this and we have to add the login route and the login function here let's send the request and we got the message invalid credentials and the status is here unauthorized so these credentials are not valid if we put the valid credentials we get the user so is that simple but we want to return the user we will return a jwd token that's why we installed zhangtung to create jwt token is really simple so the token is equal to user create token and here is the name of the token so you can put whatever i will just name it token and this is an object and to get the actual string we have to call here plain text token so let's see what this token looks like send requests again and we get a string here so this is the token that zankton generates still we want to return the token like this and what we want to do right now is set it to the cookies http only cook is especially because is more secure we don't want to return the token in the front end because other scripts can use this token and they can use data to unauthorized users so the best way to store the tokens is by creating cookies so i'll create a cookie now and the larvale has already a function for the cookies which is cookie and let's create the jwt token so this is the name the value is token and here we need to pass the time so the time it is in minutes so i will put 60 minutes times 24 so is one day you can see here that my id already hints that this is in minutes so we got the cookie now how do we return the cookie in the response so we should use this response function response and we have to pass the jade we can define a message here success so this is just a message but the actual cookie will be passed after the response so is with cookie and we have to pass the cookie here so with this we don't return the jwt is stored in the cookie where the front end doesn't do anything with it it just sends it to the back end so that is basically what we want and uh let's uh log in again so we can see cookies here we don't have any if we send a request again we get message success but we store the cookie which is http only is true and this is the value so we got the cookie also we can see the authenticated user since in the personal access token we have here two authenticated cases and that this means that laravel sanctum is working perfectly perfectly fine so the cookie is here but still the front end so we can use it via postman but the front end needs a another configuration in the course that php config course.php supports credentials to true credentials user usually are the cookies that we send so when we return the response of course postman stores it but the front end also needs to have this configuration so with this the front end will take care of the cookies as well so we have the login now let's get the authenticated user and we got it here it's super simple just like this so copy this url go to user and we don't have anything because this returns null so this means that this returns null so how do we get this user so there are multiple cases and one of them is by using a better token which i don't recommend but i will show you so this is a cookie so i will copy the cookie here and in the headers we can pass authorization bear or beer i don't know how to spell it i don't like this question mark i think the actual value is like this this doesn't work because i forgot to add something else in the routes now the user i'll move it down these are public routes it which means users that are not authenticated they can access it now this route will be you the user needs to be authenticated so we need to add the middleware so route middleware and the middleware that we want to add is auth sanctum and here will group as a function this user here so this was what was missing to return the authenticated user so let's send the request again route login not defined so to return a better message here we have to add another header which is x requested with xml http request so we got unauthenticated and why is this the case maybe i didn't want i don't need to change the token maybe try to login again so this is a new cookie i'll paste it so this should be like this so i successfully returned the authenticated user not sure why what spelling did i made i returned the message here this value so i will log in again just to show you and i will copy this bearer token and i will paste it here and now i get the authenticated user maybe when it's stored in the cookies changes something maybe that is the case so we got the authenticated user but still we don't like the better way why don't we like the better way because the front end needs to store it somewhere in order to add the bear header to this request and we want the front end only to store it via the cookies so how do we get the authenticated user when we have the cookies here so this case we have to fake it what do i mean by that so go to up http middleware authenticate here so here this authenticate extends the middleware so this middleware is this function here i will go to this function which is located in the vendor folder laravel framework src so this is the location of this file and i will copy the handle function here so you don't have to know the location of the file just write the handle function let's go to the authenticate and here i will paste this function i will also import the closure so use closure here and what i did right now is basically nothing because this function is overriding the same function now here on the header uh before authenticate we will add some configuration so we will get the jwt token so i'll make an if condition here we'll get the jwt from the cookies so we have the request here and let's get get your cookie jwd so here we'll get the jwt from the cookies and we will manually set it to the header so request headers set authorization bearer and we will attach this jwt so we are doing the same thing as a bearer before but this time we are getting the cookies from the gwd so this way the front end doesn't need to store anymore this jw team so we can remove it and let's see if we get the user we successfully get the user right now so the front end doesn't have to store the cookie it will have just this http only cookie which cannot change and we are getting the authenticated user so this is the secure way now the last function that we want to add is logout log out here and this is really simple we'll have the request here also to forget a cookie we have to cookie here sorry so we have to call cookie so this is from laravel forget jwd and that's it so don't forget also to import cookie from the facades here so that's it just return the response message success so the front end doesn't have access to the cookie it cannot do anything with the cookie and the only thing that deletes the cookie is the backend so here we need to add with cookie the deleted cookie so we don't need the request here and we delete the cookie let's add it to the routes this needs to be here because in order to log out we have to be logged in so here i will add logout and this is a post request so we are loggy logged in here now let's try to log out we'll send a post request to logout send and message success notice that the cookie is removed now if we get the user unauthenticated right now because the cookie is removed so when we open new tabs in postman the cookies will be shared across the requests so the user is unauthenticated we have to authenticate right now so we got the the cookie we don't have to do anything and now the user is returned so this is how the authentication in laravel works thank you for following this tutorial if you have anything write a comment don't forget also to like share and subscribe thank you
Info
Channel: Scalable Scripts
Views: 25,104
Rating: undefined out of 5
Keywords: jwt, jwt authentication, httponly cookie jwt, httponly cookie, laravel api authentication, laravel jwt
Id: jIzPuM76-nI
Channel Id: undefined
Length: 35min 2sec (2102 seconds)
Published: Mon Feb 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.