Nuxt Auth - Authentication and Authorization in NuxtJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
the most requested video so far by a huge margin is doing user authentication with next why three reasons first because most substantial apps require some sort of user authentication and authorization second because if most of your experience is with traditional single page web apps it's kind of baffling how a server-side rendered view app can do user auth on initial load after all server can't access local storage or cookies directly third because user auth is a multi-step process and if you mess up a single step it falls apart and because it's on the server-side debugging is a bit more challenging at least with the tools that front-end developers are used to fortunately we have knucks Toth it's a knucks module that makes all of this much simpler Nux Toth is the official authentication module for Knox maintained by Puia Parsa or PI zero online Knox doth has solutions for both local login that is username and password based authentication and oo authentication signing in with Facebook github Google auth zero or laravel passport today we're going to be only doing local login however much of what we'll learn will transfer if you're wanting to do an OAuth based login we're going to split this video up into five sections there are timestamp links in the description below if you want to jump around so first we're going to be using auth dot user the current user equivalent that Knox toth gives us we're going to do this first even though we won't see the results yet because then when we finish setting up login within the options it will tell us immediately that we succeeded and that sort of feedback is very gratifying next we'll be doing the login and registration forms these are vital to in a username and password based off system but they're going to vary a lot from app to app and that variation is not vital to understanding next off all that's important is that we're able to get a username or email in a password and then call a function when the user hits submit that's why we're going to bring in a component that I've previously created if you want to see how was made there will be a link to that video in the description next comes the meat of the experience configuring and using log in with and this is where things are most likely to get messed up if you're not careful we're going to go over what each of the options means and the different calls that log in with makes that is the different steps it goes through and then set all of that up in our app the second that it works correctly will get positive feedback because our username will display in the right side of the navbar then we'll do user notifications and errors once again we're gonna cover this quickly because while it's necessary stuff it's not court understanding next off and then finally the crowning achievement using knucks toffs and middleware to block off pages for anonymous users while still providing a blazing fast server-side rendered page to users that are logged in we'll also add a middleware of our own one that only allows users with the admin property set to true alright we have our plan and we know what we're gonna do so let's get started our first step is going to be to add the auth and Axios modules to our nook step so we're using yarn so go ahead and copy this and paste it in the command line and we'll let those install if we try to visit our page immediately you'll see that there's an error to fix this let's go ahead and restart our server next we'll have to add knucks slash off to our modules array in Knox doc config yes so we'll add that here and that will allow us to use off da logged in and auth dot user within our app let's go ahead and use that in our navbar and so that'll be in our default layout or wherever you choose to put your navbar so what we're going to do is we are going to use a V if to determine what we're going to display and so if dollar sign off logged in is true then we're going to display the username and a logout button however if it's false if the user is not logged in then we're going to display a login button and a register button so dollar sign off is something that knocks off gives us for free and it's available everywhere and it has two properties on it logged in which is a boolean and dot user dot user will have whatever properties that you have on your user so we can call things like email and then display that now let's go ahead and fill out the rest of this with our links you we'll see that since there's no user logged in will have the login and register links displaying and let's go ahead and push those to the right side of the navbar there we go and now we know that when the username shows up here that'll be a sign that we've correctly logged in so here's what we've done in this section we've installed off and Axios and then we went ahead and added them to the modules the modules is just an array of external libraries that work well with Knox and depending on how you set up next you might already have Axios installed like I did finally we took a look at the dollar sign auth object and how we can use it in our app so it has logged in which is a boolean and then user which has whichever properties you decide to put on it and here we have in our nav bar if the user is logged in it'll show the email and a logout button otherwise it will link us to login and register pages and so even though we can't see this yet it does provide us a nice link to the login and register pages that we'll be creating in the next section and it'll also mean that the second that we get logged in then will have immediate feedback and know that we're successful in this section we're going to create two new pages login and register will start with login we'll set up our login header here just so we can see that the routes working good everything seems to be flowing nicely next we'll need the actual form and for that we're going to use a component since the form will look very similar in both foggin and register call it user form because the details of this form are not essential to understanding next auth we're going to go ahead and copy and paste it from another app there's a lot here but what we'll be concentrating on are the props that we'll need to pass in if you want to know more about this component then you can go ahead and look up this video on how we built it and I'll go ahead and provide a link to that in the description below so what we're gonna need to pass in is the submit form function which will be called whenever we click the submit button then we'll need to pass in the button text which is what's displayed on the submit button finally we can optionally pass in has name and that will make it show the name field and so that's something we'll want on the user registration but not the login has a name will default to false we'll put in our button text first because that's easy we'll just have it say login then to submit form we will pass in a function and we'll go ahead and call that function login user then in our script we'll need to import the user off form then we'll put that in our components hash so we can use it and in our methods hash will put login user which for now we'll just call an alert that's just so we can see that it's working so you can see we have our login form and we need to go ahead and provide it with a valid email and we'll hit login and we'll see that everything's flowing as we expect we aren't going to do the actual login in this section that will come next section when we learn how to use Nucks Toth's login with method but we will take a quick sneak peek at what's passed in with the login info so we'll go ahead and put in a debugger and open our inspector so it caches and then we will put in something fake and login with it this will catch and see that our login info contains the email and password that we put in great so we've got the log in form displaying and when we hit submit we are passing up all the info we'll need to a method right here let's go ahead and repeat that for our register page and we can go ahead and just copy a lot of this and change some of the words you we'll also add the has name prop and make that true then you'll see that we can miss the register page and it has the same nice form except with the option for putting in a name and the button says register and of course it will call out to a completely different method so to review in this section we created our login and register pages and we created them by using the user off forum component and for us it looks like this but you don't have to understand this in particular you can use whatever styles you want in your user off forum the important thing is that when you hit the submit button then it will call out to a function and then you'll get the information that the users put in you'll need at least two items of information a unique ID such as the email in our case and then a password then you can ask for extra information in our case this is the name now we've come to the core of this video the most important part in the part that's easiest to mess up that's right we're going to actually log in using the log in with function and to make that work we're going to have to set up our options and our API endpoints in the correct way so let's go to our login page and in our login user function we'll go ahead and call login with and we're going to be using the local strategy so that's the first argument if you wanted to do an OAuth authentication then you would give the name of the Roth strategy you're using such as Facebook or github alright so the name of the strategy is the first argument and then you send in a hash and the most important part of that hash is the data hash here the fields given our username and password in our particular API we'll be wanting email and password and that's fine having that variation it's whatever your server expects that's the data you should send so here we will send in our data hash and our login info actually contains all of the data fields we'll need in this case email and password so let's go ahead and try to run this and to make it easier to run things we'll go in to our user ah form and put the default values of email and password to a correct combination and that way we won't have to type it in every time this is of course a temporary measure and we'll revert that before actually making the commit now we'll give this a try and see what happens so we'll see that it automatically made an API call to API / API slash auth / login because that is the default value of the login endpoint so this is a good time to introduce the options these are the default options for a token based workflow so in nock stock config yes we will put under the author SH or put a strategies hash and then under that a local hash and then finally under that an in points hash and if you had different strategies like github then you would put that under the strategies hash as well and it would have its own options so let's go ahead and copy these and we can start making edits we'll start with editing the URL of login to make sure it's the one that our back-end accepts so note that we have set the base URL of Axios to this so we've already got slash API in there that makes this first slash API redundant notice how it had been slash API slash API slash auth slash login so we'll go ahead and get rid of that and then we will go ahead and make it just to slash sessions so we're using the post method so that will create a new session then we'll go ahead and keep the property name as token and as a reminder so what I'm putting here is not necessarily what you should put in your app this is something you have to customize for your own back-end let's go ahead and see it working in our app so we hit login and this is successful we've gotten back a hash that has the token key on it and that is exactly what we've set it up to receipt we can also go to the application tab and see that we've gotten the token and it's set in cookies and in local storage and double-checking that is same one so if we've successfully logged in and have the correct token in our application why are we not seeing it up here that's because we need to make a second call to actually get the user and to do that we'll need to edit this hash in our back-end its sessions slash user we will keep the method name and get and then let's go ahead and check what data we get back so here we see it there's an error and it looks like it is a 401 unauthorized so there's an issue here and the issue is that the token type that we're expecting in our back end is not bear it's just blank I think that it is best practice to use the bearer token type and that's why it's a default but your server might not follow the best practice and so it's good they have this option you can set so let's go ahead and try it again with our new bearer type and it is a success we are now logged in we can reload the page and we'll still be logged in because our token has been stored in both local storage and cookies and even better so if we go to our settings and we turn off JavaScript then we reload the page we are still signed in and we can go ahead and visit the entire site of course we can't play any videos because that requires JavaScript and so it would be silly for someone to actually browse our site with JavaScript disabled but you get the idea this is just one extra thing one extra bonus that next gives you now to finish out our feature set let's make our logout button work and then let's make the register page work making the logout button work is fairly easy as long as you know the API endpoint in your server that will log you out so for us it's sending a delete request to sessions so now that we have these options set we need to go to the button itself and on a click event we'll just call dollar sign auth dot log out and now when we hit logout it automatically logs us out making it register work will take a little bit more effort but not that much because it shares quite a bit of similarities with login the first thing we want to do is update our default data to include a name and then we'll update the email so it's not a duplicate now we've got our register page set up for easy clicking but what do we do now so the first thing you should know is that next auth does not give you a register in point we are going to have to create the new user ourselves and so we'll go ahead and do that so we've got our registration info and we can just send that to our server using Axios and we'll go ahead and post and in our server it'll be two slash users which will end up being local hosts blah blah blah slash API slash users and then we'll send in the registration info that includes our name email and address as the second argument alright so if we've made that call we've now registered our user and let's go ahead and make this asynchronous real quick and this will be returning some data but you know what we don't need that data why because we don't need a user back we have their username and password right here in our registration info so let's go ahead and just use it that's right we'll just be calling login with again and this time we're just changing the name of the info or feeding in yeah registration info has a name on it but our servers just gonna ignore that and there we go once we've made those two calls we have created the user and then we've logged in so let's go ahead and try it out we will hit the register button and it is created our user and logged us in perfect let's go ahead and clean up these defaults we put in there we don't want all of our users signing in as us and then we'll do a quick review of what we learn this section so we learned how to use the login with method the first argument is the strategy we're using and the second argument is a hash and one of the keys on that hash is data and we feed it in email and password it also feed it in username and password or whatever login info you want and then to get that to work we'll need to set our endpoints in Knox config so under auth you have the strategies hash and we've set local which matches the name of the strategy here you can also set stuff like Facebook and github and then under local we have our endpoints and our token type that we've set token type by default is Bearer but your server may not process the token in that way and so we've changed ours to just an empty string and then on the endpoints for the login logout and user routes you'll need to customize those based on what your server wants you can set the URL which is the API it's called and remember the base URL property for Axios applies here then you can set the method post put delete get etc and then the property name and what property name does is when you're receiving the data back it calls that property name on the data to get the actual data that's used and this can be multiple ones chained together like here so the login with method first calls login to get the token and then uses that token to call user logout is used in auth dot log out and we use that in our logout button and we can just call it really simply like this then to register we just have to use our registration info to create a user by calling to the API and then calling login with just like we did in our login page you now have enough information to go use next auth in your own app but there's more that knocketh can do for you as well as some edge cases that you may want to cover so in the next section we're going to be looking at how errors can be handled using knucks Toth and throw in some user notifications and then in the section after that we'll be looking at the off middleware that comes with Knux Toth and create our own middleware that will restrict where users can go based on whether they're an admin or not let's start off with a seemingly simple feature and then we'll see all sorts of edge cases come up so that feature is when we log in we want to see a notification down here that says thanks for logging in and then the users name and so we've already got some stuff set up here and so we can call out to the store and dispatch to an action we've made called snack bar slash set snack bar and the arguments we passed to this dispatch to this view X action our text and optionally color by default it's going to be green and so for the text let's do thanks for signing in all right let's see this in action so first we will use a set of email and password that is correct all right says thanks for signing in great now let's go ahead and log in with a username and password that is not correct and it still says thanks for signing in so let's go ahead and see if we can get an error value from this so first we're gonna have to set this to a sink and set that to a weight and we'll get the response and then we'll set the debugger there all right let's give this a shot see if we can catch an error no we can not catch an error it's just going to give us this status code all right so if we can't reach this piece of code there is one thing we can still do we can use a try-catch block so we will stick this in the try and we'll go ahead and take out the debugger and then in catch you will try to get the error argument and we'll go ahead and log that all right so now we'll enter an incorrect combination and we'll see that we're just getting a request failed with status code 401 so that's not super helpful but since that is the most likely error we're going to get we will go ahead and translate it for the user so we'll set the color to red and the text to there was an issue signing in please try again so a little bit vague since we don't know precisely what the air is and go ahead and try it again all right that's what we are expecting so this is the way that we need to catch errors when using NOx toth that is the main lesson of this section that you need to use a try-catch block but while we're here let's go ahead and do some nice stuff for our users so in thanks for signing in we can go ahead and use the current user and because we're using a wait here we'll know that we've already signed in and we'll have access to that then after that we will use the routers push method to redirect the user to the home page instead of staying in the login page so let's go ahead and see this in action all right that's a much better experience and so the user has a lot more cues than just seeing their email appear up here now let's take what we've learned and apply it to our register function and so we'll go ahead and paste in here and edit as needed so we will of course need this first and we'll need to put in the registration info instead of the login info and just change a little bit of wording all right excellent we will test it out and go ahead and use a name that's already used and we'll see that the error is correct and then we use a new email and it registers and gives us this nice notification in this section we learned that to handle errors in knucks Daath we need to use try and catch and we also added some nice quality of life features for our users such as singing them notifications for success in for failure and redirecting them we went over all this quickly because it's not strictly part of Knox toth but in the next section we will cover a core part of Knox tothe which is the auth middleware and we'll see how to expand on it so we have our working login and register pages but users that aren't logged in can still access every single page on the site we'd like to be able to restrict access to certain pages based on whether a user is logged in and different attributes of the user the way that you might do this in view router is not available we don't have those hooks and next but there's a new way to do it and that is through a middleware so next off comes with the auth middleware automatically so we're putting that in the admin page which means that oh hey look we were redirected from admin to login and if we try to go to one of admins child pages videos for example then it will still redirect us so with this one line we've been able to protect the admin page and all of its children but that's not quite good enough so if we register someone then no matter who they are they can still access the admin page so now for this case we need to make a custom middleware and so there are two ways we could do it we could stack it with the auth middleware so author ins first and then admin runs but I don't see a whole lot of upside to that since we don't want to assume that auth will always run the for admin and if we're checking that the user is an admin will already be checking that they're logged in so let's create a new middleware called auth admin so the basic form for a middleware you export default a function and that function has a context object and we can go ahead and make this a sync as well and that context will contain a lot of things the first of which will care about is dollar sign off let's go ahead and extract our user from that all right so we have our user and if we have our user and the user is an admin then we can go ahead and let the user in otherwise we'll want to redirect them to the home page redirecting them we'll use the next function and then we'll go ahead and get the store as well and we'll go ahead and dispatch an error message now when we click the admin link as a non admin user it gives us an error and when we log in as an admin user then it allows us to visit the page of course that's not the best UI showing people a link that they're not supposed to click so let's go ahead and fix that so in our default layout we'll go ahead and add a V if here and so if we have auth dot user and auth dot user is an admin then we will show the admin button and we'll see that it is still visible when we are signed in as an admin but then we log out it is no longer visible no longer tempting people but if we type it in then well it just completely airs on us and that is because server-side rendering does not like the next function so we can replace it with the redirect function honestly I think that's better named anyways alright so now we can go ahead and type in admin and oh good look it redirects us but turns out server-side rendering doesn't like our snack bar so we don't see that message if you have the type of app where you're going to have a lot of users that don't really understand the system getting linked to pages that are behind this sort of wall then you may want to redirect them to some sort of page to ask them to log in and shows an explicit message saying they don't have permissions but for our purposes this is fine so to review in this section we first learned about the auth middleware which comes out-of-the-box with Knux Toth it will block off pages and make sure that users that aren't logged in won't be able to access them and it will also do it for all the children of the pages that you mark with it then we created the auth admin custom middleware which also makes sure that the user is an admin and then if they're not we show them a message and redirect them to a different page we have learned a lot in this video so let's do a quick review that hits just the highlights so we have the dollar sign off variable which is available in all of your components and it contains logged in which is a boolean or user which is something you've fed in from the server and it also contains several methods like logout and login with login width is probably the core method for knucks Toth and it looks really simple here and once you have your options figured out it is simple but you have to make sure to line up those options with what your API expects so first with the data you're sending you have to make sure that you're getting the correct information so for us it's email and password or it could be username and password or something like that and the rest of the configuration happens in nook stock config yes so under auth strategies local we have a set of several options so a token type which is by default bearer we can change to any type we want and then we have an endpoints hash and we need to define boggin logout and user so these are the URL that we'll call and the method that we'll use and then for Vagan and user because they return data the key that will have that data so when you call login with what it's going to do is it will first call to whatever URL you put in log in and then it will take the result from that the response and grab the key that you put in to property name and assign that as the token that token will then be sent up in every access request including the request to user which is sent right after login returns and from that you get your actual user all right so we've defined all these endpoints and they're used in login with and locking with is used again in register as well as login because in register we'll just treat the new user and then login with them and also note that wrapping this in a try-catch block that seems to be the best way to handle errors when using Knox toth then finally we have our middleware so we have off by default and we created our own auth admin and we have to be sure to use redirect rather than Next and that is all for this video if you want to learn more go ahead and check out the documentation it provides details on all the other our capabilities of Knox toth including but not limited do all those other providers you can use once again thank you for watching and I hope you enjoyed it if you did enjoy it consider subscribing to my youtube channel there are a lot of videos just like this on different topics and there are going to be a lot more soon you
Info
Channel: Vue Screencasts
Views: 107,437
Rating: 4.8622384 out of 5
Keywords: Javascript, vuejs, vue, javascript frameworks, web development, frontend javascript, nuxt, nuxtjs, ssr, auth, authentication, authorization, server-side rendering, nuxt tutorial, vue tutorial
Id: zzUpO8tXoaw
Channel Id: undefined
Length: 44min 57sec (2697 seconds)
Published: Wed Oct 30 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.