Node Auth Tutorial (JWT) #15 - Protecting Routes
Key Takeaways
Protects routes using JWT in Node.js
Full Transcript
all right then gang so in this video what i want to do is take everything we've done so far and use that jwt that we send back when we log a user in over here we can see that and we're going to use that to authenticate a user on the server for every subsequent request so we can start to protect routes from people that are not logged in alright so we're going to do that in this video but there's one quick thing i want to do before we do that and that's just to add a couple of links up here in the header one for the sign up page and one for the login page so i've already opened up the header.ejs file and underneath the h1 inside the nav i'm just going to paste in this ul two li tags each one contains a link the first one go into forward slash login for the login page and the second one going to forward slash sign up for the sign up page this one has a class of button which is styled inside styles.css just to make it into a button all right so if i refresh now we can see both of those up here login takes us here and sign up takes us here so then see now for example i only want people who are logged in to be able to see this page right here which is reached by going to forward slash smoothies so i want to protect this route from unauthenticated users right but how do i do this well remember for every request that we make to the server the cookie and the jwt inside that crooked that we have right here is sent to the server as well so if we send a request to get the smoothies page by clicking on that button on the home page then on the server we can check the jwt that comes with that request now if this jwt is present and it's valid as well then we can send back the smoothies page because then we're considering the user to be authenticated or logged in if it's not present or it's not valid for example if it's been tampered with then we can redirect them to the login screen so they can log in first of all so we need to do two things right here first of all we need to detect that the jwt cookie exists on the request because if it's not there then they're not logged in then we'll just redirect them here to the login screen secondly we need to verify that the jwt is authentic and it hasn't been edited or tampered with and based on that we send a response all right so to do this we are going to create some custom middleware and then we can apply that middleware which checks all this jwt stuff to the routes that we want to protect does that make sense all right so to do this i'm just going to create a folder over here let me close all these called middleware now you don't have to put it in here i'm just trying to keep my code organized so i can see at a glance what everything is and then if i open this up i'm going to create a new file called auth middleware.js all right so that the first thing i need to do inside this file is require the json web token package because we're going to use that to validate or verify the json web token so let me just paste that in remember we installed that earlier and then we need to create this middleware function so let's call this require auth because this middleware is basically going to check the authentication status and we're going to apply this middleware to any route that requires authentication all right so that makes sense so i'm going to set this equal to a function and inside this function we'll do something in a minute but first of all remember inside any middleware we get access to the request object oops i don't know what i've done there rendering something the request object and also we get the response object and we get the next method as well and at the end we always have to call the next method remember okay so we'll do that shortly so the first thing we want to do is grab the token from the cookies so remember because we use the cookie parser we can say something like this const and we want the token so we'll call it token and set it equal to the request dot cookies now we want a cookie called jwt so we can say dot j wt that's what we call the cookie remember and that's what it's stored as over here in this application tab all right so we're grabbing that token now now it might exist it might not so the next thing we need to do is check do we have the token so i'm going to place a little comment here first of all check json web token exists and is verified right or valid so we need to say if token so this will be true if there is a token if there's no token and we don't have this jwt cookie then this is gonna be false it and it's not gonna fire so if we have this we're gonna do something if we don't have this we're gonna do something else right and the other thing that we're gonna do is redirect them to the login screen because if we don't have a token we're not logged in so let's redirect them somewhere where they can log in so we can do that by taking the response object and redirecting to forward slash login just like that so say for example we place this middleware function in front of some route like forward slash smoothies it's going to fire this first of all right and if it finds that there's no token then it's not going to carry on with the request handler for that route because it's just going to redirect to this page okay so if we have the token at that point what we want to do is try to verify the token now to do that we can use a method on this jwt package so i can say jwt dot verify so this is the method we're going to use to verify a token we pass in the token which we have from here and as a second argument we pass in the secret which we used and it has to be the same as the secret that we use to sign the tokens now if we take a look inside the controller up inside this function we use this secret right here so we need to grab that and we need to paste it here because ultimately what's happening is we're taking the jwt that comes with the signature right and we're going to try to basically recreate that signature based on the headers the payload and this secret and if the signatures match after we've done this then we're saying yeah this is valid this is a valid token so this thing right here takes a third argument which is a function and that fires once this has checked it now this function takes in two arguments it takes in an error if there's an error and the decoded token if we manage to decode the token and there's no error all right so inside this function first of all we need to check is there an error because if there's an error then it means that the token is not valid and at that point again we want to redirect them to the login screen so let's grab that and paste it inside an if check to see if there's an error so if error and we want to redirect them if there is let's also log to the console the error.message all right so then if there's an error we're doing this if there's not an error at that moment in time what we need to do else is then say okay well we'll just log the decoded token to the console so we can see that and then we're going to use this next function to say well now you can carry on with what you were doing so at that point it would carry on with the handler function for the forward slash smoothies route which is then going to send back the smoothies view all right so we can carry on and do that and it does that by your saying next now i am going to log like i said to the console the decoded token so console.log decoded token all right so that's all there is to it we're now creating this function right here this middleware function which we can place in front of any route that requires authentication if they are authenticated if we have the token and this is valid then we're going to just fire the next function and that basically lets it carry on with the next middleware and that would be the middleware inside the route handler for forward slash smoothies so if we take a look in app.js when we go to forward slash smoothies it's this thing right here and it would render that view so that's if we have a token and it's verified if we don't have a token then it's going to redirect to login if we have a token but it's not valid then it's going to redirect to login and we never get to see this thing right here the smoothest view it never gets to this because we don't say next we just redirect all right so the next thing we need to do is export this function so let me say module dot exports is equal to an object and inside there we're going to export require auth like so all right so now we have that we want to place it in front of this function right here as middleware so it's going to fire right about here so i'm going to say a require auth oops require auth like so now we need to import this function so let me grab it and up here i'm going to say const and we want to grab the required auth equals require and we're going to get this from dot forward slash middleware to go into the middleware folder forward slash auth middleware so this should all work now if we're authenticated we should see the smoothies page if we're not authenticated then it's going to redirect us to forward slash login now i'm going to cross my fingers because there's probably going to be some kind of error that i don't know about but at the minute right i am not logged in if i delete that jwt if i refresh over here we don't have that token so if that's the case i'm not logged in right and if i go to the smoothies page by clicking this button i shouldn't see it it should redirect me to the login screen so let me try that there we go it works it doesn't let me see that screen okay cool now if i was to log in mario at google.com and the password is test12 and if i log in we get the jwt right here now if i try to go to the smoothies page now i can see it because this is present it's being validated on the server or verified and it's seeing me as logged in therefore it just says next okay you go on carry on what you were doing you can render this view right here to the user and they can see it because they are authenticated so now we could use this middleware on any route that we wanted to if we really wanted to we could make it so the page required authentication and therefore we couldn't even see the home screen without being logged in so if i was to open up this and delete the jwt and then try to go to the home page i can't even see the homepage now because i'm not logged in alright so this is a nice little mid-aware function we can apply to any route that we want to protect from unauthenticated users
Original Description
🐱👤🐱👤 JOIN THE GANG -
https://www.youtube.com/channel/UCW5YeuERMmlnqo4oq8vwUpg/join
----------------------------------------
🐱💻 🐱💻 My Udemy Courses:
+ Modern JavaScript - https://www.thenetninja.co.uk/udemy/modern-javascript
+ Vue JS & Firebase - http://www.thenetninja.co.uk/udemy/vue-and-firebase
+ D3.js & Firebase - https://www.thenetninja.co.uk/udemy/d3-and-firebase
🐱💻 🐱💻 Course Files:
+ https://github.com/iamshaunjp/node-express-jwt-auth
🐱💻 🐱💻 Other Related Free Courses & Links:
+ Node.js Cash Course - https://www.youtube.com/watch?v=zb3Qk8SG5Ms&list=PL4cUxeGkcC9jsz4LDYc6kv3ymONOKxwBU
+ Get VS Code - https://code.visualstudio.com/
+ JWT Debugger - https://jwt.io/
🐱💻 🐱💻 Social Links:
Facebook - https://www.facebook.com/thenetninjauk
Twitter - https://twitter.com/thenetninjauk
Instagram - https://www.instagram.com/thenetninja/
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Net Ninja · Net Ninja · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
Related Reads
🎓
Tutor Explanation
DeepCamp AI