Node Auth Tutorial (JWT) #9 - Cookies Primer
Skills:
Backend Performance60%
Key Takeaways
Explains cookies in Node.js authentication using JWT, including setting and reading cookies, and discusses CSRF attacks
Full Transcript
all right then gang so before we jump into working on the authentication process itself i think it's best to get a basic understanding of cookies and how they work so this video is going to be a quick primer for cookies but feel free to skip if you already know how to use them with express applications so cookies basically give us a way to store data in a user's browser so that data could be anything we want it could be a name numeric values etc they can also be used to track your internet activity by services like google analytics but how do they actually work well when a request is sent to our server we can create a cookie at that moment in time and we can decide at that point what data the cookie will hold as well as things like how long the cookie should last inside the browser before it expires and it's automatically deleted so the cookie is then sent back to the browser in the server response and the browser registers it so now that cookie is storing data inside the user's browser now every request the browser makes thereafter to our server it sends whatever cookies we stored to the server with that request and on the server we can access it so this process is the backbone of how we'll be authenticating users whereby this cookie holds a jwt to identify a user and when the server sees that they can verify and authenticate them now there is more to it than this and like other authentication processes there are pitfalls and things to be aware of when using cookies and jwts such as cross-site request forgery whereby potentially malicious websites can essentially steal a user's authenticated status to make harmful requests to a server now in our case that risk will be low because we won't be exposing any state changing endpoints to logged in users so the worst thing that could happen is that we reveal hidden pages and the malicious site couldn't change any user data but if you are creating a website with state changing endpoints for authenticated users where the data could change then you will definitely need to research csrf mitigation strategies and put those into place to protect your data now i will leave a link to a good bit of information about this down below and i would recommend reading that but for the sake of our tutorial and learning about the process since we're not going to be exposing those endpoints we're going to carry on as is and continue to learn about cookies all right then so i'm in app.js and i've just created two dummy routes here to test out cookies so we have one called set cookies and that is a get request and we have a get request for read cookies as well so we're going to use this one and visit this in a browser if we want to create a cookie and we're going to visit this one in the browser to read the cookie so first of all let's set the cookie how do we set a cookie so imagine someone comes to this url in a browser at this moment in time we want to create a cookie and register that in the browser well very simple to do all we need to do is get the response object and then use the set header method to set a header now the header we want to set is the set cookie one and the second argument here is going to be basically the cookie value now the cookie value has to have a name and a value so the name is going to be new user and i'm going to set that equal to some kind of value like true okay so this is how we identify the cookie the name of it and this is the value of it and this my friends when we send a response to the browser is now going to send this cookie along with it so it will register that in the browser so i can say down here response dot send just to send some plain text you got the cookies all right so i suppose that shouldn't be plural at the minute because we're just sending one but doesn't really matter if i save this now i'm going to go to the browser and i'm going to go to forward slash set cookies which is this url over here where we set the cookie and when we go there we should get this response but we should be able to then also see this cookie in the browser so let me go here set cookies and we can see you got the cookies now if i go to this application tab over here then we're going to see if we go to cookies and our local host website right here let me just make this a bit bigger that we have this new user cookie and the value right there is true so this value is now being stored in the user's browser now notice a couple of things here we have this expires property and that says session and that means basically whenever i close the browser then this cookie is going to be deleted from the user's browser so if i then come to the website again and go to a different url not set cookies then i'm not going to have this in my browser however if i now just go to a different page on this website altogether without closing the browser i still have this cookie it's here for the session until i close the browser all right so that's how we can set a cookie that was pretty simple right now by the way if you go to the console you can access the cookies inside here by saying documents dot cookie and this is how we do it from javascript we use the document object and we can access that string where we have new user and that's equal to true so we could do something with this in the code if we wanted to all right so that's the kind of basic way to set a cookie however there is an easy way to work with cookies and that is by using a third-party package called cookie parser so what i'm going to do is install this let me scoot this up and open up a new terminal then i'm going to say npm install and it's called cookie hyphen parser like so so i'm going to install that make sure it goes into your dependencies over here like this and then we can import it or require it in this file now i'm going to do that right at the top over here so i'm going to say const cookie parser you can call it what you want this is just a variable name but i'm going to set it equal to require cookie hyphen parser okay so this thing right here that we require this is actually a bit of middleware a bit like we used middleware right here to pass json data we're going to use the cookie parser make sure you spell this correctly parser to pass cookie data so i'm going to say down here app.use to use this middleware and all we need to do is pass in this function so cookie parser like so and invoke it so now we've done that we can access a cookie method on the response object so let me show you how that works so down here instead of setting the cookies like this now we're going to do it using the cookie method instead so i can say response dot cookie like so and if i want to give this cookie a name it's the first argument and that is new user and then the second one is going to be the value which is going to be false and this does the same thing as this up here okay but it looks a little nicer it's easier to use and it's also going to be easier to access later on when we come to read cookies so initially this was true now we're creating a cookie and setting it to false now what's going to happen here because we already have a cookie in the browser called new user well if we create a cookie like this it's going to basically look for that cookie in the browser if it exists already it's just going to replace it and update the value of that cookie if it doesn't exist it will make the cookie right so it currently exists but the value over here is true but if i now refresh then we should see the value becomes false because now we've reset it to be false all right okay so let's try making another one i'm going to say response.cookie and then this time we're going to create a cookie called is employee like this and then we'll set that to be true okay so if i save this and comment of a heart then we should see in a second this one right here is employee let me just make this a bit bigger and that is true now there is also a third argument we can pass into this cookie method and that is an options object so i can pass an object right here and i can specify different properties inside this object for example i could say the max age and i could set in milliseconds the age of this cookie now remember by default the age is session so whenever we close the browser that's when the cookie gets removed however i can override that behavior here by setting a max age of an hour or three days or whatever you prefer so let me just paste this in and this is basically a day 1000 milliseconds times 60 seconds to get us one minute times 60 minutes to get as one hour and times 24 hours to get us one day so this is one day in milliseconds right so that will be the max age of this cookie now and it will be removed from the browser after that amount of time now if i close the browser and reopen it it's still going to be there so it doesn't expire when the session ends now it only expires after this amount of time okay so that's the max age what else can we do we can do something like secure and set that to be true now what does this do this means that the cookie is only going to be sent when we have an https connection a secure connection now we don't have that at the minute as is http by default so if i was to delete this right here this cookie right and save over here if i refresh again then i'm not going to get that cookie because this now is only going to be set over a secure connection so let me just come over here i've refreshed to show you this we don't get that second cookie we get the first one because we don't have secure set to true on this but this one is not set all right now let me delete that we can also use a property called http only like so and i could set that to be true and that basically means now we cannot access the cookie from the javascript so you know before i said document.cookie to get the cookie values like this and we got them now if i set this to be http only it means we can't access it from the front end and they can only be transferred via the http protocol so back and forth between the clients and the server not in the front end javascript so i can demo that i'm going to save this now and i'm going to refresh over here we should get that cookie now because we took off the secure option so let me go to cookies oops this hasn't worked let me refresh and if we go to cookies we can see is employee that's set to true but this thing right here now is checked http only for this cookie so we can't access this now from documents dot cookie like this we don't see it in there but if i take off this property let me get rid of that and just keep the max age now if i come over here and refresh then hopefully we should see that this tick is not going to be there anymore it's not and by the way you should see the new expiry date for this thing over here because we set that as well but now i can say document.cookie and we're going to get both of those values is employee and new user all right so both of those two different properties are very important when it comes to auth because in production first of all you should only use authentication cookies over an https secure connection and you don't want them to be accessed or modified by the client side code either okay now for the sake of this tutorial we're not using https but be mindful you should always be using an https connection for authentication purposes in production so for now all i'm going to do is keep the max age there and also i'll say http only to make sure it's not accessed in the front end as well and set that to true okay so how do we then read the cookies because i said earlier when we get cookies in the browser if we then go to another url for example just a home page or whatever on the server when we receive that request we can access the cookies and since we're using the cookie parser up here we can access them on the request object much like we did on the response object right here so i could say over here that const cookies is equal to a request.cookies and by the way we can access this in any handler because we've used that cookie parser so any request we send to the server to any url in any handler we can access the cookies all right so now we have those cookies what i'm going to do is log them out console.log so cookies like so now i'm also going to send a response so response.json will send and we'll send along the cookies because that at the end of the day is just an object over here for us it passes the cookies into an object for us so we're just going to send that back as jason to the browser okay so let me save this and now if we go to forward slash get hyphen cookies then hopefully this is gonna work okay no that didn't work let me refresh okay not worked oh that's because it's read cookies not get cookies under okay read and now we see these cookies right here new user and is employee and also over here we should see logged to the console if we go to the other terminal these cookies right here now the good thing is because this is now a javascript object we can use dot notation to get the different cookies that we want to access and we just use whatever name of the cookie we give it so if i were to access the new user i can say dot new user to grab that cookie spell this correctly okay save it and now if i refresh over here then hopefully this should work okay and we can see that that value is false so then my friends that is the basics of how cookies works which is nice to know when you're creating an authentication process which uses them under the hood so next up we're going to look at how json web tokens work which we're going to be using alongside cookies to implement our authentication system
Original Description
In this video we'll talk about cookies in general & how they can be set & read from & on the server.
More about CSRF attacks - https://owasp.org/www-community/attacks/csrf
🐱👤🐱👤 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
More on: Backend Performance
View skill →Related Reads
📰
📰
📰
📰
7 Apache Kafka Design Patterns Every Backend Engineer Should Know
Medium · Programming
Symfony Validator: Where Framework Validation Ends, Domain Rules Begin
Dev.to · Gabriel Anhaia
Seu status de pedido não devia ser uma string
Dev.to · Denis Augusto
From a Go CLI to a full developer ecosystem: Gopher Glide for IDEs
Dev.to · Shiyam
🎓
Tutor Explanation
DeepCamp AI