Authenticating a Laravel API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right hello everybody christopher wray what's up welcome to the stream today to our tech talk i'm in uh twitch mindset right now but welcome everybody this is the first one i'm doing on our youtube channel so that's a lot of fun today we'll be talking about uh authenticating a laravel api and well let's preface this with this is being recorded this will be on youtube the recording will be and we are going to email you this as well for the recorded link if you have any questions please post them in chat we're able to see the chat and uh hang out and answer those to do introductions my name is chris on code i am the founder of a website called scotch.io i'm a dev advocate at digitalocean and today i'm a really big fan of laravel so i get to do a lot of laravel work today and i know that laricon online is running right now so we're gonna do our best to get this in quickly so you can get back over to those fantastic talks over there so here we are at digilotion.com shout out in the comments if you've ever used us scotch.io has always been hosted on do so that's fun um this is our tech talk today authenticating a laravel api and uh hey sarah so here we are digitalocean youtube channel this is where everything's going to be hosted and that'll do it for our introduction type stuff so let's talk about laravel and all the great things that come out of the box for it so laravel gives you so much stuff out of the box and one of the things it does do for us is authentication and the thing about this talk and there's a question in chat about it is there are so many ways to authenticate a laravel application that there are going to be like four different ways and let me open up vs code real quick where'd you go this is how i do slides i don't really do real slides so if we're talking about ways to authenticate we have um we have the built-in laravel authentication right we have the guards which are laravel guards which you can bring a jwt library and this is the way we're going to do it today and we're going to set this up so that this will be a little bit of a quicker webinar we usually do like an hour long webinars we'll take this down to like about 30 40 and then we'll set up the next ones for the other ones which are really popular laravel socialite for social logins we'll set up laravel passport which is the oauth implementation we'll set up one for kind of a newer one laravel sanctum and uh we'll set up another one also after here for laravel i don't know i typed in laravel all the time but authorization so a lot of that is going to be uh all the different things that we'll talk about so i'm sorry about it but today we're going to talk about the jwt implementation because sometimes you don't need to reach for the passport implementation and the skystat io implementation was all just a jwt and the authorization stuff we'll talk about a little bit today but we will deep dive into it in another one and also socialite passport sanctum so uh i hope everybody's good with that the passport one i'm really excited to get to so we'll get that out to you as fast as possible and we'll schedule that for one of our next tech talks to get us started i'm gonna open up my terminal here i have everything in a folder called batcave and if i ls there i have a folder called laravel apps i'll cd into that and once we're in here i have this setup with laravel valet which is what we use to kind of uh host all of our local applications and have them running so i'm going to go ahead and go laravel new jwt auth we'll just leave it at that while that runs while that runs let's talk about some stuff in this order yes i believe all of this stuff will be in this or actually let's move socialite out because socialite isn't really an api auth type thing this is more of the api off type stuff and then socialite is kind of just a front level authentication that we'll also keep but i believe that will be our order for our auth series so stay tuned for that we have our app running let's open it up in code what do we call jwt auth okay so here we are in code let me change out our php color in here no okay whatever um so while we're in here let's talk about setting up our laravel app i don't need our terminal anymore i'm going to do the built-in vs code one so to start us off we have our dot env file i want to get this done quickly let's change our db connection to an sqlite connection while we're working locally it's easier um remove the status bar there remove the activity bar here get you some more room and while we're here um we have sqlite as our database and then we need to create an sqlite database or go touch database database dot sqlite so now we have a folder over here database now we have this database.sqlite file and now we can go one more setup thing and i know this is a lot where are we at there we are we'll open this existing database which will be under batcave laravel apps jwt off database database sqlite so this is our database that we'll be working in today uh christopher ray with the question in chat can we pair laravel authentication with this method with jwt auth yes so the cool thing about the laravel authentication is that they use what are called drivers so that you didn't have to and if we go to config off.php let me zoom out here if we go here we have our defaults guard is web and the password that we're going to check on is the users so down here authentication guards we have one for the web which is what you use by default in a laravel application and that's like if you have any blade views that you want to authenticate on there you use this but if you're doing an api which a lot of us are doing these days with headless cmss and all that good stuff in the jam stack api is the guard that we'll be using and here driver token we're gonna bring out our own jwt package not our own uh the jwt auth package and then we'll change it here and automatically all of the things that laravel gives us out of the box for authentication we'll just go ahead and use that package and the cool thing is if we're talking about actually let me open up routes api.php so if we're talking about authentication stuff we have our auth helper where we can say auth user right we can basically use that anywhere in our application to grab our user and the other thing that laravel brings us is middleware so we can say auth api there so all of our requests to this specific route have to be authenticated using the api um guard so on the web side of things if you wanted to use middleware there it wouldn't be the auth api it would just be auth and that's because in the auth.php the default is web so if we change this to default being api which we are about to we can go over here and we need we can drop this colon api and that'll be our authentication question in chat how secure is jwt off in general i would say it is very secure and it's been the way that apis have been authenticated for i would say the past 10 years or so right and it is very secure there are just some gotchas that you need to make sure of is that when you're storing things in your so let's talk about the flow and then we'll talk about the downsides to jwt auth um and we'll also talk about off zero which is a third party implementation of authentication so we have normally you have a login so this is you'll like my slides so the um let's call it server side off way so the server side offway is user visits browser right user logs in with form from browser and then once the request is made to our laravel back-end the laravel keeps user information or user session so basically laravel authenticates that user based on their email and password and then says oh you're authenticated i'm going to keep this in memory keeps user off uh info and then every time a user hits back to the session wearable will say okay this is our user we're all good there but the api sideway and the reason we don't we want to change it out with the api side versus the server sideway is that we don't want any sort of um session info stored on one server and this is really cool because once we move to the api way of authentication and we don't store anything on a single server we can now span our application across multiple servers and be globally distributed this is one of the things that i had trouble with scaling scotch.io once we hit around four million page views it got really tough to have a single server serving all of that so switching over to api authentication where there was no server we were able to kind of move a lot of our server logic into different places and put it behind a load balancer so the api sideway user visits browser user logs in with form but that isn't really where the magic happens laravel authenticates user and gives a token and this token ajwt is what is going to be used for the user to kind of come back and use that jwt user requests info from api with jwt so that's kind of like a quick rundown of the differences and the jwt way the downfall is where you store it in your application on the local side so level doesn't care about the jwt about keeping that so that's the user or the browser's responsibility right so the browser would usually put it in local storage in cookie in some kind of storage on the front end and whenever the user comes back we would add it to a an http header for uh called authorization so let's do all of this right now right here in this webinar in this tech talk uh yes with the question i wish 4 million page views per day no that's a monthly account all right so let's delete all this let's delete this so the package we're going to use today is jwt dashoff.com this is a super popular laravel package for json web tokens so i don't want to walk you through the install here but let's go down and actually do the install so we'll go i'm getting confused i have two of these open let's close this one um hold on okay so let's open up our terminal again let's expand this out a little bit and then let's do composer require time on slash jwt off and yeah if you have any questions please throw them in chat thanks everybody for being here while this runs so to set us up for more stuff um normally you would add this to your providers array with level 5.4 or below we don't need to do that anymore which is cool so we do need to publish our uh config file so let's do that next once this is all done maybe i need a faster computer okay um anybody in chat also following along with laircon online so while that's running let's go ahead and do some routes for what we want to accomplish today let's do a create create a user route so if we're going to authenticate users we're going to need a user to be able to authenticate against let's do a login a user log out a user and then let's do right on thank you yeah so if you're wondering what my theme is i am using monacai.pro and you can go to that in your browser and then also my font is cascadia code which is a free font okay so create a user route let's go ahead and do that because we don't need our jw2 package for that so let's go route get um user or let's go user dash create function request i should have a snippet for this i just reset up this computer so let's go for um app user create and we're going to need an email a name and a password um so let me double check i think we missed the step right here okay so this is installed but we did miss a step on our setup we need to mark migrate that's coder thanks for that uh glad you're here and nwi development aren't we storing something local browser side anyway so the jwt sounds similar yes it is similar um the session stored on the server sideway in our cookies so yes it is a little bit different it's just that the server sideway is something we don't have to manually manage ourselves and this way there's just a little bit of extra work on the back end and the front end okay so let's go name chris on code and if you want to chat with me my names are always open on twitter um my email at digilotion.com i try to get chris but it was already taken uh and then password we need to hash it so let's do let's go grab the hash uh helper here use illuminate who remembers these facade ash okay so let's grab this hash one and then we'll go down here and we'll say hash make password um well that's not secure so let's do my super duper secret password so if we hit this route it should be able to create a brand new user for us and we should be able to see that user in our database where are we let's go to insomnia and if you're wondering why i'm using insomnia over postman i think it's faster and personally i like the ui a little bit better postman has a lot of stuff going on so let's go new requests create a user and we call this jwt auth.test is where our local server is slash api slash user create um questions in chat i could use the bcrypt function huh that's probably easier i'm just used to using this and you're right it should be facades um where am i facades sorry okay so let's go back here and yeah be crypt would work as well i gotta take a step back i'm bouncing everywhere okay so let's go back into insomnia we'll send this request i am using valet yes so now this is returning 200 uh we didn't return anything out of this out of this route so nothing came back but our user should have been created so let's go down here sql pro let's go to the users table let's go to data we have our user now cool and there's our hash password cool so if we go back over to our vs code now log in with the user we should be able to and i'm going to do some wishful coding here we should be able to route get set up a new computer but i don't have any of my snippets um login so we'll do function right here request i'll just try to type as fast as i can request um so we're going to say credentials is equal to and let's just copy these two up here so ideally and this is our wishful coding part we're going to say we're going to say token is equal to auth and the um the string that we want here is going to be attempt sorry the method we want here is attempt credentials so this should be our jwg token that's kind of our wish for how things go and then we just go return token and we'll return that back to our user they can store it however they want and then on subsequent requests they'll send us the token after that so let's go back into our uh terminal and make sure we can get all of this set up for jwt auth now that all that's done installing let's do the php artist and vendor and i'm just copying off their docs blah blah blah so php artisan vendor publish is what we want to do here so that created a config jwt.php and i always like looking through these after they're created jdlt authentication secret is there off keys over here public key private key so one of the things we're going to talk about in a future tech talk will be laravel sanctum which is a way that you can issue api keys per user so a user can have multiple api keys with multiple accesses for each key and that's actually a really really cool package that we'll talk about and the last part of this let's just uh create a jwt secret so that is set right there and now we should be good to go um oh thank you test coder for that i just copy and pasted the wrong things so credentials should have password wouldn't that be bonkers if somebody let you authenticate with just name and email so that goes right there so notice that we're hashing it here um and the question is kind of like hash or bcrypt they both are the same thing i just used hash because i was used to it um but i think lately i've been leaning more towards using just the helpers like this instead of using the facade for it and that's just me it's easier to write you don't have to do the import right let's see so those are credentials our password we're going to send in uh from our browser which we'll go grab these ideally we should grab them from our api request right so that should be credentials is equal to request only and it'll be email password is that an array that has to happen or no i don't know anymore so once we're there um let's go and see that is an array come on chris okay so let's do that instead of this we'll comment that out uh other parts of setup for the gwt stuff and let's blaze through this so we can actually use it um we need to go into our user model and import the jwt subject we need to implement and there are two methods we need to add to this user model we need to add let's do it at the bottom public function get jwt identifier so this is basically saying the identifier you can make it your email you can make it id whatever you want so we're gonna say return this get key so whatever laravel by default is gonna use as the key for this model is what we're gonna use and then the last one public function get jwt custom claims this is something that you can add to your jwt token so that it can be added to any information like roll maybe or something like that you can add so that it sends it back to your ui so that your ui can say oh hey this is an admin i should be able to show them like this section of the ui okay so is that all we need for our setup we have one last thing okay one last thing we go into our auth config guard is api but down here right here under api instead of token we're going to say jwt so now laravel knows okay i'm going to use that package to do all of my authentication cool um test coder is correct with where's my api with this request helper we don't need this right here so you could have done this as a request like that or you could totally just do a request helper uh this i added just out of habit i always type it pretty much but that's correct thanks test coder okay so let's try this out log in route we pass in an email and a password and we should get a token back cool so let's go here we're going to create a login request we're going to say http jwt dash auth dot test api slash login and let's go with a multi-part form here we'll say email see sabaleja digitalocean.com password is i should have just said password my super duper secret password and one other thing is uh yeah that should be good let's send it nobody returned for the response let's see what happened here so let's um i've always had trouble with this let's do a json real quick so that um one of the things that the level api likes us to do is do content type application json so let's send it some json that's supposed to be email sorry and this is the cevaleja digilotion.com this will be password my super super secret password send that now we get a token back which is really cool so what we can do is we can actually talk about this jwt token so if we go back to our browser jwt dot io is a good resource i believe off zero put it out yep um so all zero great at handling third party authentication if you need that so here's their debugger that they give us you can paste in in a gwt and kind of see output from it so here a jwt is three parts the header the payload and a verify signature part so they are separated by periods here there's one part there's two part period and the third part so if i just paste that in right um we have the issuer here which is jwt auth test api login and all of our information kind of in here so kaylee what we're doing here is we are decoding a jwt and let's see if this works actually let's go grab in our jwt dot config or it should have been in yeah it's in our environment file down here if we throw in this jwt secret all the way over here oh i see okay that wouldn't really do much for us so um what we're doing is basically sending this jwt over to our users and then our users are responsible for storing that and using it for sending into our api so once we have this let's go back to our api.php we have get login right we have log out a user let's do get a user so get a single or get the authenticated user so let's do a route get uh me and normally if you're doing this uh these would probably be like post routes actually that would be a get this would be a post request right there uh so route get me and you would want to put some middleware on this or off and the get request and my syntax is all wrong but there we go so let's do function like that so this is a way that we can get the login in user we just say return auth user and again you'd probably want to um route is defined as get for login how are you getting post form data so if we go back to our um insomnia request here if i change this to a post request i can hit send and i'll get this but now if i change it back to the get request it won't work 405 method not allowed does it answer the question um but yeah so if we go back to the post request we get our token nice i'll copy that and let's go and create a new request get login user so this will be http um jwt auth dot test slash api slash me if we send it right it'll error out because route login is not defined oh i see um so this tried to redirect us back over to a login page so it's essentially treating it like it's a normal uh browser request for laravel to treat this as an api request and return json data we have to say content dash type application json json json so once we have this we're going to um just add an authentication so normally you could do this here as a header authorization bearer and then paste in that big old token that we just got and now we're able to get our user out of that json token and that's all there is to handling authentication with jwts so a lot of that is set up for the jwt package right but let me try to clean this up a little bit this was creating a user so the two mains that happened here are one login so you basically give a user a token here and then two you are going to check the token by using this middleware right here for auth and uh you can also do the auth api one if you didn't have the api guard set as default so then you get the user here so once you have the user then you can do whatever you need to with the user like return user id you can use their id to go get like their posts or any sort of thing like that that may be associated with the user model which these days everything's associated with the user model right so that kind of wraps it up for this jwt authentication and earlier we had talked about doing some more of these so i wanna we're experimenting with like the length of these tech talks let us know what you think about like the 30 to 40 minute length that this one was or if you would have wanted it to go to the full hour and maybe done a little bit more um we're liking these bite-sized ones right now the next one we'll do was authorization because once we have a user authenticated and let's say we have a post model we only want the owner of a post to be able to update that post so authorization is in its own right a full talk that we'll do and then passport is the next one after that so between password and uh i must i think that says jots json web tokens which one is the most preferable authentication in laravel as always uh it depends if you need something that's pretty quick and easy and all you're doing is all you're doing is these quick authentications where you have a user and they have to do some crud on a certain resource then i would recommend just using the jotway if you're doing a little bit more complex stuff then definitely bring in passport and if you're doing even more complex stuff or you want to be simpler about your logins you could bring in a third-party service like off zero right so let's see um also another thing that's kind of in the middle between passport and this jwt solution is sanctum so level sanctum lets you issue access tokens to users for specific things and passport does that as well but it gives you a lot more control over like the scope of each access token all right some votes for full hours well thank you for the feedback everybody cool you're welcome christopher wray sarah vieira uh yeah how good is level auth for an e-commerce web app i would say larry veloth is fantastic um very secure the difference the cool thing about laravel auth is that laravel auth can still be laravel off but you can use a different package for it so like let's say here i'm using auth user that's a laravel thing but here under our auth config i'm using the jwt package which is a third-party package so fabian that's right it's the accept uh is the right here accept application json and then let's uh drop that send yeah so if you do accept application json then you get uh json back json data back json i i know i switched like 100 times but if we send that it'll treat it as a browser request it'll send you back to a route which we never defined a login view so that won't work so thank you fabian for that uh yeah any other questions before we wrap this up get everybody back to uh lericon online cool so hayden i think a lot of good resources would be closer to learning about json web tokens and authentication in general so jwt.io is a very good resource and it kind of leans into all the technical tutorials that off0 has jwd's or passwords or passport better uh for that question we will do a deeper dive into passport and i'm i'm pretty sure that one will take us an hour um passport has a little bit more of granular control over what tokens can access right so passport and let me open up the docs for passport real quick so passports um can manage tokens uh manage clients request tokens uh do tokens per client right so there's a lot of granular control that a token can have so like a single token can have access to certain models and another token can have access to certain models so you get all of that control using passport and it is a little bit more work but if you just need hey i need to authenticate a user and make sure that they can get into my app then the gwt way is good it looks like there's a lot of questions on passport so maybe we'll do that one before the authorization one but the authorization one is kind of necessary knowledge moving forward so yeah the passport one and the authorization one will take up the full hour that's a big a big subject for each of those so yeah thank you everybody for joining we'll wrap it up right here um as always you can find us digitalocean on twitter you can find our youtube channel uh just slash digitalocean uh you can find me on twitter at chrisoncode so i'm happy to answer any dms there but yeah thank you everybody authorization then passport thanks arthur yeah i think that's the correct progression from jwt authorization passport and then we talk about sanctum and then we bring it back to web authentication with socialite cool all right well we'll wrap it up everybody have a great rest of your day thank you for hanging out with me for uh 40 minutes so i'll see you all later
Info
Channel: DigitalOcean
Views: 24,714
Rating: 4.8508773 out of 5
Keywords:
Id: TTK8uQOjpT0
Channel Id: undefined
Length: 38min 42sec (2322 seconds)
Published: Wed Aug 26 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.