Getting Started with Vue.js Navigation Guards to Restrict Access to Routes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone NIC Raboy here in this tutorial we gonna see how to use navigation cards in a view j/s project so you might be wondering what is the navigation card so these are often also called nav cards or route guards and what they do is they give you more control over navigation in your pjs project or if you're using angular or react they have similar concepts in those frameworks as well and they I think they're even called the same thing but this is a view jazz tutorial and where you might want to use a navigation card is maybe when it comes to authentication of different areas of your application so for example maybe your user has to log in and they log in and it's validated against some remote server that server says yes you're now logged in no you're not logged in in the occasion where they are not logged in well maybe we don't want them to view certain pages of your application and then maybe when they are logged in then those pages become accessible to them so this this is where navigation card guards could become useful it's by no means the only circumstance that you could be using them for but it is a it is a common scenario and that's what we're gonna be exploring in this particular tutorial so I do have a terminal open I am navigated to my desktop what we're gonna do is we're gonna create a new project we're gonna see how to use these navigation guards in action so what I'm going to say is I'm gonna save you I'm gonna say create I'm gonna call it nav project I'm gonna choose the defaults and we're gonna add certain features as we go along all right so we've got our project what I'm going to do is I'm going to open that project I'm going to be using Visual Studio code for this particular example use whatever you feel the most comfortable with this is just a text editor so what I'm going to say is I'm gonna first navigate into nav I'm gonna say code and I'm gonna open it so as you can see we do have our project open I'm gonna open up my terminal within Visual Studio code so that way we can continue to use the terminal kind of within our editor experience before we start editing any files we need to get two more packages included in our project so the first of which is we're gonna say npm install and we're gonna say view x and we're gonna say - - save so this is going to be our datastore to be used within our application view access it's very common we're also gonna install another one we're gonna say NPM let me first clear my terminal here MPM install we're gonna say view router and we're gonna say - - save so again the view X is going to be used for storing our credentials after logging in and we're just gonna simulate a login we're not gonna actually connect to any remote server in this example but we will be kind of mimicking what would happen in a real scenario so I'm gonna clear my terminal the next step that we want to do is we want to create various components that will represent our routes so navigatable areas within our application so let's go ahead and open up source we're going to open up components we do have a HelloWorld component let's just go ahead and clone that so I'm going to say copy and I'm gonna paste it into components and we're gonna be ignoring the HelloWorld component long term but for now let's just go ahead and rename this let's go ahead and rename this - may be secured of you so this secure dot view file is going to represent where we want our user to end up after they sign in but we don't want this secured up view file accessible unless they are properly authenticated so let's go ahead and clear out a lot of this project file we're gonna clear out what's inside of the template we're going to clear out our Styles because this is just going to be a very basic application we are gonna leave the style tags there just in case we want to revisit them towards the end and I'm gonna fix the indentation for my script because I'm using four spaces as my tabbing whereas I think it defaults to two when you spin up a new project and it's just more of a sanity thing it'll drive me crazy if it doesn't match properly so we're gonna rename this let's just go ahead and maybe call it secure inside of our template maybe let's add some some text to say that hey this is a secure page so I'm gonna say div so let me fix that we're gonna say maybe h1 maybe this is a secure area we're gonna say maybe P so for paragraph let's say this is a secure area so nothing nothing very complex here this is gonna be just very basic HTML the whole purpose here is to show that hey we made it here and we used navigation cards in the process we're also gonna wipe out these properties we're not gonna use properties on this because it's gonna represent a route not an actual component that we're gonna recycle throughout our application but this this should be good now it's it's very basic but it's gonna work alright so let's create another component I'm just gonna copy this secure component because there's not a whole lot in there when I say copy I'm gonna paste it into the components directory and I'm gonna rename this to B let's go to save login dot view so for now let's go ahead and wipe out what's inside the template let's go ahead and change the class name - let's say login and what we can do is we can actually start adding various HTML components so this is gonna represent our form so what the user types in for a username and password and then some very basic logic for validation so let's go to let's go ahead and set up the data that that the user can provide and work with so we're gonna save data this is gonna be our models for binding binding our data to the form so data return we're gonna say let's go ahead and say that this is gonna be inputs for like form inputs you can you can name it however you want how whatever makes the most sense to you but let's say that we're gonna have an input for a username and we're gonna have an input for password let's go ahead and say that we're gonna have a few methods so again this is inside of our view class so we're gonna say methods we're gonna have a method called login and when we try to log in we're going to do some very basic validation so we're gonna say if this dot input dot username and because we define it on line 13 and 14 if that equals again we're hard-coding it here because we're not gonna use a remote data service definitely don't hard-code this in your application this is just for demonstration purposes of what we're gonna be doing with the nav guards in reality you're gonna want to make an HTTP request and you're going to want to validate that way so let's go and say if this equals admin we're also gonna say and this input password equals let's go ahead and say pass then we know that the user has provided the correct login credentials and I feel like I need to reiterate this one more time don't hard-code this in production this is for testing purposes only we're gonna say else and we're gonna say maybe console dot log and we're gonna say the username or password is not correct and this is gonna be evolved as we go along and for now we're not gonna have any kind of logic inside of here yet because we're not working with view X but we will so this should be good for now what we could do is that we let's actually before we move along let's go ahead and create that form because that will bind our username and password give our user something to type in let's go ahead and say maybe h1 we're gonna say log in page inside of here we're gonna have an input let's go and say that this is typed next let's go ahead and say that the name of the input is going to be username we're gonna bind it so we're gonna say V model equals we're gonna say input username because this is this username this input username is our variables which were then working with in our method so that's our V model we're gonna have a placeholder let's just go ahead and say username we can close that tag let's go ahead and do another line here I just cloned it this one's gonna be the password I'm going to bind it to input dot password the placeholder is gonna be password and it's not going to be of type text it's going to be of type password so that way it's masked and then finally let's have an input so that way we can submit our form and call that login function let's go to say button we're going to say type equals button we're gonna say V on click equals login and that's gonna be that login method and we're gonna say let's call this login button so so we have a very basic form and if I were to run this nothing would happen because I'm not first of all I'm not calling this component directly and we haven't set up our router as of yet so that's gonna be one of the next steps but before we actually even set up the router we're gonna do some more boilerplate kind of bootstrapping of our project we're gonna configure view X so let's go ahead and go to our main dot J's file inside of our source directory so this is gonna be where we set up view X first of all we need to import it so I'm going to say import view X from I'm sure I'm sure I'm saying view X wrong it's probably called something else but I know it as view X we're gonna say view X the next step and you can have a semicolon there or not but the next step is we need to initialize it so let's go ahead and say view dot use view X because that's what we just imported and we're gonna we're gonna define our store so we're gonna say constant store equals new view X dot store and we're gonna define some mutation functions as well as some data that can be mutated so let's go ahead and say first of all let's go ahead and say that we have a state that state has a variable called authenticated false and the goal here isn't to show you how to use view X it's not even to show you how to use the router we're gonna be showing how to use the the navigation guards but again this is all set up so that way you are kind of on your way to being successful with this all right so we have authenticated as false that's the default value here let's go ahead and set up our mutations so this is gonna be how our components can actually interact with that authenticated variable so I'm going to say mutations this is going to be an object let's go and say set authentication we're gonna have that state and we're gonna have a status so we're gonna say state dot authenticated equals whatever the user provides is a status so this is gonna be just a true or false so that's our store it's by no means a complicated store and compared to what it could be but it'll it'll serve its purpose for this example let me go to fix the indentation for render h here what we're gonna do is we're also going to add store now so we're gonna say store and that's gonna be store right here so store being one of the properties that you could have for view this part being what we've defined as a constant on line 9 so we save it we're good so far the next step here is well we want to try to use the view store so we've defined in main Jess let's go ahead and drop back into login dot view this is where we're gonna define our logic here on line 24 in our login function and all we're really gonna say is we're gonna say this dot dollar sign store dot commit so we're gonna commit a change to the variable so the mutation that we're gonna call asset authentication and the value that we're gonna set is it's gonna be true so it's gonna be authenticated otherwise it's gonna remain false and nothing is going to have changed so now let's define our router so this is kind of where we get into the core subject material I know that I know that we've dragged on a little bit because you really wanted to see well how do I use a navigation guard but I didn't want to just drop you right into navigation cards because then you might be lost in regard to this setup so we're going to go back into main j/s we're gonna add some things now remember we've already imported the view router so we're gonna save import view router from view router we're also going to import each of our routes so each of our two components so we're gonna say import log in from component slash login dot view and it's actually components I'm also going to import secure so we have both of our components here and they're they're a little grayed out because we're not using them yet but we will so just like we did with using view X we're gonna save you use we're gonna say view router we're also going to define the routes for that router so we can do that after store let's go ahead and a semicolon there for consistency but we're gonna say constant router equals new view router and let's go ahead and add our routes so we're gonna say routes this is going to be an array we're gonna say path so this is going to be the default path so this is the route path what we're gonna do is because we don't really have a route path we don't have a home page we're just going to assume that the first entry point into this application is going to be the login page so we're gonna redirect we're gonna redirect to log in which we're going to define in a second and it's actually it's actually yelling at us here because I just have an array it should be an object so an array of objects all right so it's gonna redirect to login we're gonna create login right now again this is the kind of the default page so this is another object we're gonna say path this is gonna be login it could be anything you want but this is just what we're gonna define it as because it kind of makes the most sense we're gonna say name so this is login again this could also be whatever you want it's just gonna match what we have on line 31 here what matters really is the component so the component we're gonna say that it's gonna reference the actual components of login dot view that we created with the form and the and the very brief login logic that kind of stuff so that's what's important to us then finally we have secure so this is another object we have path this is going to be secure we have name this is going to be secure we have component which is going to be secured out view so secure and if we wanted to this would technically work although we don't have route guards yet so let's go to wire up the router we're gonna test it out we're gonna see why the navigation guards are are helpful to us and they're going to add those navigation guards so down in the view constructor here let's go ahead and say router it's gonna reference the router that we had just defined I'm gonna save it I'm gonna run it it hopefully it should work so I'm going to say NPM run serve we've got an error somewhere console dot log unexpected console statement this is probably the linter the linter probably doesn't like what we're doing here so we're just gonna comment it out so it's not going to do anything it's fine we'll make it work so it's gonna run it it's running on port 8080 so let's go to our web browser let's go to localhost 8080 so ever view app the problem here is you know what we've got this old template from the hello world so that means that we we haven't really finished configuring everything so we're gonna let it run still it's still serving what we actually want to do is we want to go to the app view file we need to make some changes we can remember it right now it's using hello world still we're kind of scrapping this mentality so let's start removing things let's let's remove the styles let's remove a lot of the template here and instead what we're going to do is we're gonna use the router so we're gonna say a router view and let me fix let me fix the tabbing because again it will make me crazy personally so we have a router view this is going to be where each of our routes render into what we can also do is we can remove this hello world we're not using it anymore and let's go ahead and fix the indents here so that should be good I don't need this import anymore it's not it's not necessary let's go back into our Google Chrome or whatever browser we're using and you can see here that we've got a login page so let's go and test it out test test nothing happens admin pass again nothing happens because we don't actually have any redirects happening so let's let's go to make some changes let's go back into our visual studio code we'll go back in to login dot view right after we set this commit and again no navigation guards are happening yet but let's go and say this dot dollar sign a router dot replace so we're gonna replace the current route so we're gonna say name is going to be secure so remember we have a we have a route called secure and that's what it's using so I saved it go back into my Google Chrome I'm gonna say admin I'm gonna say pass and click login took me to the secure area I'm gonna just refresh the page here so I'll refresh it I'm going to try to go directly to secure and I was able to when i refresh the page actually it should have cleared anything that I had in that view X store so as you can see I was able to directly navigate to this secure page and this is this is what we want to prevent in the long term here we we don't want users to be able to access this unless they are truly authenticated so and now to the kind of core material of this what this video is meant to provide if I go to sick not sick he remained Jas you'll notice that this is a very small addition to our project but if I go to this secure route I can add to it I can add my navigation card so I could say before enter I'm gonna say to from and next so this is this is where we gather information about the route that's happening on the routing event that's happening so what I'm going to say is I'm gonna say if the store so the current view X store if the state of the authenticated variable is equal to false that means we're not authenticated we should not be able to visit that secure page so what we're gonna say we're gonna say next is going to be false now else we're gonna say next with nothing in it so what we're saying is when we say next is equal to false we're saying don't proceed to the route do not continue routing to the secured page just stop otherwise if we have no false in there we're saying you know what let's go ahead and allow the user to reach this particular route and we can make adjustments in a second but I'm gonna save it I'm gonna go back into Google Chrome I'm gonna say that I want to refresh it I'm going to say secure and nothing happened which is exactly as it should now let's go to login now so let's go ahead and say admin pass login now I'm in that secure area if i refresh it it may take me back I took me back to nowhere because it didn't know what to do so this is where we can actually optimize this instead of saying false we can provide it a path to go to instead so what we can do is we can actually say login so we're saying if if up indication is false let's redirect that user back to the login page so they can proceed to logging in so let's go and try it out let's go ahead and type in secured took us to login let's go login here looks good so far if i refresh it took me back to login page because if i refresh that stores cleared out I should not be authenticated so here should not be navigatable - so instead it redirects me to the login page so there are actually other types of events that you can catch during the routing process but before enter is a good example of one so in this case we've just detected you know where where is the user trying to go are they properly authenticated or are they allowed to go to that that area otherwise stop them or send them somewhere else so this this very small chunk of code is actually what this tutorial had set out to prove I know that we did a lot of setup we created two components a login component which which has a form and some authentication logic a secure page which is a secure area that we wanted to protect we have the main.js file we created our view X store which which wasn't entirely absolutely necessary but it was good because we were able to access that store inside of the navigation guard but it was just a lot of set that led us to these few lines so this this could be very valuable to you again don't don't hard-code your your login and also you probably want to have other means to check authentication status I mean don't rely strictly on your front-end to protect pages instead maybe maybe you want to check to see if a GWT token is stored and then if yes allow them to navigate through and then you know what they're probably just gonna make an HTTP request from that secure page for actual data so it's all up to you on how you decide that you want to design it but this this is some good code that will protect various routes that you have in your application for view you
Info
Channel: The Polyglot Developer
Views: 16,168
Rating: 4.857605 out of 5
Keywords: vue.js, javascript, web development, navigation guards, route guards, authentication, authorization, programming
Id: 30XtkPC8nHI
Channel Id: undefined
Length: 24min 53sec (1493 seconds)
Published: Wed Nov 06 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.