Learn JWT in 10 Minutes with Express, Node, and Cookie Parser

Web Dev Cody
31 Mar 202110:19

Summary

TLDRThis video offers a concise tutorial on integrating JSON Web Tokens (JWT) with Node.js and Express for secure authentication. The host demonstrates creating a login system with JWT, explaining the process of signing tokens using a secret key, setting expiration times for added security, and utilizing cookies to maintain user sessions. The video also covers middleware for verifying tokens and handling token expiration, providing insights into the structure of JWTs, including headers, payloads, and signatures. By using jwt.io, viewers learn how to decode and validate JWTs, ensuring a foundational understanding of implementing secure authentication mechanisms in web development.

Takeaways

  • 😀 The video provides a five-minute overview of using JWT (JSON Web Tokens) with Node.js and Express.
  • 🔐 JWT can be applied across different programming languages and frameworks such as Python with Django, PHP with Laravel, etc.
  • 📝 The demonstration includes a server.js file hosting an Express application with specific routes for login and adding data.
  • 📑 The application has static files like an index with a login form and a welcome page for making basic requests.
  • 🍪 The application uses cookie-parser middleware to handle JWTs and set them in the user's cookies for session management.
  • 🔑 JWT signing involves creating a hash using a secret key, which ensures that only the server can generate valid tokens.
  • 🗓️ JWTs have an expiration date, with shorter durations being more secure, and the video demonstrates setting an expiration time.
  • 🍪 After a successful login, a JWT is set in the response header as a cookie, which the browser uses for subsequent authenticated requests.
  • 🛡️ Middleware is used to verify the JWT from the cookie for secured routes, ensuring that only authenticated users can access them.
  • 🛑 If a JWT is invalid or expired, the server clears the cookie and redirects the user back to the login page.
  • 🔍 The video concludes with an explanation of JWT structure, including the header, payload, and signature, and how to use jwt.io to decode and verify tokens.

Q & A

  • What is the purpose of the video?

    -The purpose of the video is to provide a five-minute overview of how to use JSON Web Tokens (JWT) with Node.js and Express, and to demonstrate the process with practical examples that can be applied to other languages and frameworks as well.

  • What are the main components of the JWT example in the video?

    -The main components of the JWT example include a server.js file hosting an Express application, a login route, an add route, static files like index and welcome pages, cookie parser setup, and middleware for authentication.

  • How does the login process work in the JWT example?

    -The login process involves a POST request to the login endpoint where the username and password are verified against the database. If the credentials are correct, a JWT is created using the user object, a secret key, and an expiration time, which is then sent back to the client as a cookie.

  • What is the significance of the secret key in JWT?

    -The secret key is crucial for signing JWTs. It ensures that only the server with the correct secret can generate valid tokens, preventing unauthorized access to the server's endpoints.

  • Why is the expiration time important for JWTs?

    -The expiration time is important for security reasons. It limits the lifespan of a token, reducing the window of opportunity for an attacker to misuse a stolen token. Shorter expiration times are generally more secure.

  • How are cookies used in conjunction with JWTs in the example?

    -Cookies are used to store the JWT on the client side. After login, the server sets a cookie with the JWT, which the browser then sends back with future requests, allowing the server to authenticate the user.

  • What is the role of middleware in the add route?

    -Middleware in the add route is used to check for the presence of a JWT cookie, verify its authenticity using the secret key, and decode the token to access the user's information, such as the user ID, before proceeding with the route's logic.

  • What happens if a JWT is expired or invalid?

    -If a JWT is expired or invalid, the server will not be able to verify it, and the middleware will follow an else path, which typically involves clearing the cookie and redirecting the user back to the login page.

  • How can one inspect the contents of a JWT?

    -A JWT can be inspected using a tool like jwt.io's debugger. By pasting the token into the debugger, one can see the split parts of the token, including the header, payload, and signature.

  • What is the composition of a JWT token?

    -A JWT token is composed of three parts: a header, a payload (or body), and a signature. The header typically includes the token type and the signing algorithm, the payload contains the claims (user data), and the signature is created using the secret key, header, and payload.

  • How are the header and payload of a JWT encoded?

    -The header and payload of a JWT are Base64 encoded strings. This encoding allows the information to be included in the token in a URL-safe manner.

  • What can be inferred about the security of JWTs from the video?

    -From the video, it can be inferred that JWTs are secure when used properly with a strong secret key and short expiration times. However, they can be vulnerable if the secret key is compromised or if tokens are intercepted by an attacker.

Outlines

00:00

🔐 JWT Authentication with Node.js and Express

This paragraph introduces a tutorial on implementing JSON Web Tokens (JWT) in a Node.js Express application. The host explains the setup of a basic server with routes for login and adding data, along with static files for login forms and welcome pages. The focus is on the login process, which involves a JWT library to sign and verify tokens. The server checks the username and password against a database, and upon successful authentication, it signs a token with a secret key and an expiration time, then sends it to the client as a cookie. The explanation also covers the security aspect of using an HTTP-only cookie and the process of making authenticated requests with the JWT stored in the cookie.

05:01

🛠 Middleware for JWT Verification and Token Expiry Handling

The second paragraph delves into the middleware function used for verifying JWTs in the Express application. It describes the process of extracting the token from the cookie, verifying it with the secret key, and decoding it to access the user information, such as the user ID. The middleware sets the decoded user information on the request object for further use in secured routes. The paragraph also discusses handling scenarios where the token is invalid or has expired, demonstrating how the server automatically clears the cookie and redirects the user back to the login page. Additionally, it provides insight into the structure of JWT tokens by using jwt.io to decode and analyze a token, explaining the header, payload, and signature components.

10:02

📚 Conclusion and JWT Token Composition

In the final paragraph, the host wraps up the JWT overview by inviting viewers to leave comments or questions and encouraging subscription for future content. They also provide a brief explanation of what a JWT token is composed of, mentioning that the body and header are base64 encoded strings and the signature is a hash created using the secret key, header, and payload. The host illustrates how the signature ensures the token's authenticity and integrity, and how tampering with the token results in an invalid signature, leading to logout and redirection to the login page. The paragraph concludes with a base64 decoding example to show the simplicity of the encoded parts of the JWT.

Mindmap

Keywords

💡JWT

JWT stands for JSON Web Token, which is an open standard for securely transmitting information between parties as a JSON object. This is the central concept of the video, as it demonstrates how to use JWT for authentication in a Node.js and Express application. The script explains JWT's role in creating a secure login system where a token is issued upon successful authentication and is then used for subsequent requests to access protected routes.

💡Node.js

Node.js is a cross-platform, open-source JavaScript runtime environment that executes JavaScript code outside a browser. In the context of the video, Node.js is used as the server-side platform to create an Express application that handles JWT-based authentication. The script mentions setting up a server.js file which hosts the Express application.

💡Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for building single and multi-page, and hybrid web applications. The video uses Express to create API endpoints for login and adding data after authentication. It showcases how to set up routes and middleware to handle JWT tokens.

💡Authentication

Authentication is the process of verifying the identity of a user, device, or system. In the video, the authentication process is demonstrated through a login endpoint that checks a user's credentials against a database. Upon successful authentication, a JWT is issued, which is then used to authenticate subsequent requests.

💡Secret Key

A secret key in the context of JWT is a private piece of data that is used to sign the token, ensuring its integrity and authenticity. The script mentions using a secret key ('hello' in the example) to sign the JWT, which is crucial for verifying that the token has not been tampered with.

💡Middleware

Middleware in Express is a function that has access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The video script describes using middleware to verify the JWT from the cookie before allowing access to a protected route.

💡Cookie

A cookie is a piece of data stored on the client's browser by the server. In the video, after a user logs in, a JWT is stored in a cookie and sent with subsequent requests to authenticate the user. The script explains setting a cookie with the JWT and using it for maintaining the user's session.

💡Environment Variable

An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer. In the script, an environment variable is used to store the secret key for signing JWTs, which is a common practice to keep sensitive information out of the source code.

💡Expiration

Expiration in the context of JWT refers to the lifespan of the token, after which it is no longer valid. The video script discusses setting an 'expires in' property for the JWT to one hour, demonstrating how to make tokens time-sensitive for security purposes.

💡HTTP Only Cookie

An HTTP only cookie is a cookie that is inaccessible to client-side scripts, such as JavaScript. This helps mitigate the risk of client-side cross-site scripting (XSS) attacks. The script mentions using an HTTP only cookie to store the JWT, which adds an extra layer of security.

💡Base64 Encoding

Base64 is a binary-to-text encoding scheme used to represent binary data in an ASCII string format. The video script explains that the header and payload of a JWT are base64 encoded, which means they can be easily decoded to inspect the contents without losing the data's integrity.

Highlights

Introduction to using JWT with Node in Express for authentication.

Overview applicable to various languages like Python with Django, PHP with Laravel.

Server.js file hosts an Express application with specific routes for login and adding data.

Static files include an index with a login form and a welcome page for basic requests.

Use of cookie parser to store JWT in user's cookie for session management.

JWT signing process explained with 'jwt.sign' function using a user object.

Importance of a secret key for signing JWT to prevent unauthorized token creation.

Setting an expiration date on JWT tokens for enhanced security.

Demonstration of setting a cookie in the response header after user login.

Explanation of using HTTP-only cookies for added security.

Middleware for verifying JWT tokens from cookies in secured routes.

Process of invalidating tokens when they expire or are tampered with.

Visual demonstration of JWT token in browser's cookie storage.

Using middleware to extract and verify tokens for protected routes.

JWT token's composition explained with header, payload, and signature.

Using jwt.io debugger to inspect and validate JWT tokens.

Base64 encoding of JWT token's header and payload.

Hashing process in JWT signature for token verification.

Summary of JWT usage in Node.js for secure and practical web development.

Transcripts

play00:00

hey everyone i hope you guys are having

play00:01

a great day welcome back to another

play00:02

webdav junkie video and so in this video

play00:04

i want to give you a five minute

play00:05

overview

play00:06

of how you can use jwt with an example

play00:09

of using a node in express

play00:11

but you can take these ideas and apply

play00:12

to whatever language you want like

play00:14

python and django php and laravel but

play00:16

let's just dive into it to save some

play00:18

time

play00:18

right here i have a server.js file which

play00:20

is hosting in express application

play00:23

and the main thing i want to talk about

play00:24

in this app is we have a url

play00:27

called slash login and we also have a

play00:28

url called slash add

play00:30

but these are the main things we're

play00:31

going to focus on but just to kind of

play00:33

make sure you're not in the dark we do

play00:34

have two static files that are hosted we

play00:36

have an index file

play00:38

that is located here that has a form and

play00:40

a login button

play00:41

and then we have a welcome page which

play00:42

also has a button that just makes

play00:44

a really basic request to the ad page

play00:46

and then finally we have a cookie parser

play00:48

set up

play00:49

so that we can take the jwt and put it

play00:51

in the user's cookie so we have a login

play00:53

form here and we are going to hit that

play00:54

login endpoint so i do have a

play00:56

test username typed in and a password

play00:58

typed in and so when i click on login i

play01:00

want to show you what kind of happens

play01:01

so it's going to hit this express

play01:03

service and it's going to go to this

play01:04

login route okay so inside of my routes

play01:07

folder i have a login

play01:08

file and let me just walk you through

play01:10

this code real quick we are basically

play01:12

including a json web

play01:13

token package or library which allows us

play01:16

to sign and verify jwt tokens and

play01:19

this is the end point that we're hitting

play01:21

and to kind of walk you through this

play01:22

really quick

play01:23

we grab the username and password that

play01:24

came over the payload

play01:26

we checked in the database for that user

play01:28

based on the email they provided or

play01:30

username they provided

play01:31

and then we verify is the password

play01:34

that's stored in the database

play01:35

matching the one that the user sent in

play01:37

in the login page if it's not we just go

play01:39

ahead and throw an error back

play01:40

but the important part of this whole

play01:42

endpoint is the

play01:44

signing process so we have a jwp.sine

play01:47

function call here

play01:49

and we are taking that user object that

play01:50

we got back from the database

play01:53

and we are just signing it okay so what

play01:54

that means is it takes an object

play01:56

and it basically will look at

play02:00

the payload and it'll create a hash and

play02:02

put it

play02:03

as a signature at the end of the jwt and

play02:05

we'll we'll talk about this at near the

play02:06

end of the video of how a jwp is

play02:08

composed but a second important part to

play02:10

point out is that we have to provide a

play02:13

secret here so you notice here we have

play02:14

processing be my secret

play02:16

so when i host my server this is

play02:18

actually set to

play02:20

i think hello so let me refresh this

play02:22

yeah so this is an environment variable

play02:24

that i set to hello here

play02:25

and that is what we're using to sign our

play02:27

jwt this is important because

play02:29

this prevents anyone else out there from

play02:31

just creating jwts

play02:33

and hitting your server to try to access

play02:35

it right they have to know the exact

play02:36

same password that your server used

play02:39

in order to create a jwt token to uh

play02:42

hit your endpoint and then the third

play02:43

thing that's really important to talk

play02:44

about is

play02:45

the expires in property here so usually

play02:48

jwt tokens

play02:50

have an expiration date and the shorter

play02:51

they are the

play02:53

more secure the safer i'm just going to

play02:55

do one hour here to kind of show you but

play02:57

typically you want to do like 15 minutes

play02:59

10 minutes 30 minutes

play03:02

um and so we create this token and that

play03:04

is what we can use as kind of like the

play03:06

key

play03:06

that the user can use to hit our

play03:08

endpoints and we can verify that hey is

play03:10

this user actually the correct user uh

play03:12

so after we have the token

play03:13

we are going to set a cookie on the

play03:16

response header so that the browser can

play03:18

actually say hey

play03:19

i have a cookie i need to set in my

play03:21

browser and keep track of it

play03:23

and then later on the browser will send

play03:25

that cookie when it does for

play03:26

future requests uh some things i want to

play03:28

point out here is it's

play03:30

usually most safe to use an http only

play03:32

cookie

play03:33

there's also some other flags that you

play03:34

can look into if you want to make this

play03:36

more secure

play03:37

but i'm not going to do that in this

play03:38

example and then we redirect them to a

play03:40

welcome page so let's just go back here

play03:41

and click that login button

play03:43

the first thing i want to show you is we

play03:45

hit that login endpoint here

play03:47

and we are doing a post request to that

play03:48

endpoint but the important part is that

play03:51

the response comes back

play03:53

with a set cookie in the header right so

play03:55

this is that token that we're talking

play03:57

about

play03:58

and the server told our browser that we

play04:00

need to set that cookie

play04:01

so to further exemplify that let's click

play04:03

on this application tab

play04:04

and let's go down here to storage where

play04:06

it says cookies

play04:07

and click on our url so you'll notice

play04:09

that the cookie is actually set

play04:11

with this token keyword and we have the

play04:14

cookie or we have the jwt token here

play04:16

right we're going to talk about the

play04:17

token

play04:17

uh in just a bit like what this actually

play04:19

is because it looks like a

play04:20

random jumble of characters but just

play04:24

know that whenever we make a

play04:25

future request that token is going to be

play04:28

put

play04:28

onto a header so let's further check

play04:31

this out we have a button here on the

play04:32

welcome page which just does a post

play04:34

request to that slash

play04:35

add in point okay so before i click it

play04:39

let's go back to our server notice that

play04:41

we have an ad in point

play04:43

but the main difference with this route

play04:44

is that we do have some middleware set

play04:46

up to make sure that the cookie is

play04:47

provided so

play04:48

this is like a secured route we don't

play04:50

want anyone just hitting this endpoint

play04:52

we want someone who is authenticated

play04:54

and we want to maybe check their user id

play04:56

to do some logic

play04:57

so before we do the logic we're going to

play05:00

use this middleware function to

play05:02

basically take the token out of the

play05:03

cookie

play05:04

and verify it all right so here we are

play05:07

saying get the token

play05:08

based on that token key that we talked

play05:10

about here

play05:12

get the token out of the cookie and then

play05:14

we verify it okay so this is

play05:16

a library function call we can do

play05:19

basically passes a token

play05:21

then we also pass it that secret key

play05:22

that we talked about earlier

play05:24

that we used for signing the token and

play05:27

if the token that came in

play05:28

has the exact same key in the signature

play05:31

as the one that is set here then this

play05:34

will just work it'll return the

play05:36

decoded token to us which happens to be

play05:38

that user that we sign here

play05:41

and then we can access things that we

play05:42

put on that right so for example the

play05:44

user id

play05:45

but in this middleware i'm just going to

play05:47

set it on my request and call next which

play05:49

will allow us to go to the next step

play05:52

in the route endpoint which happens to

play05:54

be this ad route

play05:56

which will just basically redirect us to

play05:57

a welcome page

play05:59

so let me just go ahead and click that

play06:00

and show you

play06:03

so notice here it did a request to the

play06:05

add page again that

play06:07

that cookie was set in the header here

play06:09

we have that cookie here

play06:10

and the server basically took that

play06:12

cookie verified it

play06:14

and called the next um step in the

play06:16

process which is redirect to welcome

play06:18

and notice that we also got a request to

play06:20

welcome because our browser was

play06:21

redirected to it let's talk about the

play06:24

other scenario where the token is

play06:25

invalid or the token was expired okay so

play06:28

let's go back

play06:29

to our login and let's make this expire

play06:31

after one second

play06:32

so now if i were to go back and kind of

play06:35

clear out my

play06:35

cookie here and go back to the login

play06:38

page

play06:39

if i were to type in that same stuff so

play06:42

notice that when i log in we still get

play06:44

that cookie but

play06:46

now since it expires after one second if

play06:49

i make this request here it's actually

play06:50

going to take this

play06:51

else path which is going to clear the

play06:53

cookie for us automatically

play06:54

and redirect us back to the login page

play06:57

let's just go ahead and click that and

play06:58

you'll notice that the cookie

play07:00

is removed from the cookie section here

play07:03

we don't know

play07:04

we don't ever have a token and we are

play07:06

back at the login page so that is my

play07:08

like

play07:09

um invalidation logic setup uh and i

play07:11

think that's about it so let's change

play07:13

the

play07:13

the expires back to an hour the last

play07:15

thing i want to show you all though

play07:16

which is kind of important is like what

play07:18

is a jwt token like what is it made up

play07:20

of

play07:21

so what i'm going to do here is i'm

play07:22

going to make another token

play07:24

let's just go ahead and grab that jwt

play07:26

token and i want to paste it into a

play07:27

website

play07:28

called jwt dot io alright so if you go

play07:31

to jwt io

play07:33

and go to this debugger section you can

play07:34

actually paste in your token and what

play07:36

this does is it's going to

play07:37

split apart your token into the various

play07:39

parts and kind of show you what it's

play07:41

made up of so

play07:42

every token usually has a header section

play07:44

which is this red section

play07:45

it has your payload or your body which

play07:48

is the purple section

play07:49

and then it has a signature okay so this

play07:51

signature

play07:52

is created using that secret key that we

play07:55

set in our server

play07:57

and then also with the header and the

play07:59

payload so basically takes the header

play08:00

and the payload

play08:01

and the secret creates a hash and it

play08:04

puts that at the end of your jwt token

play08:06

again this allows us to basically verify

play08:09

that any token that comes to our server

play08:11

has the exact same hash that we expect

play08:13

because we are the ones who know

play08:15

how to sign and verify tokens with that

play08:19

secret key

play08:20

what you can do here is if you were to

play08:21

paste in some random stuff like

play08:23

i'll just type in some random characters

play08:24

and paste our existing token

play08:26

notice down here it says invalid

play08:28

signature

play08:29

but if i were to put hello

play08:33

and replace our signature notice that it

play08:35

says signature verified so this is

play08:37

basically the same steps our server

play08:38

server's taking it's just using this

play08:40

secret string of hello

play08:42

and making sure that this is token was

play08:44

actually issued by myself

play08:46

by my own processes and if it wasn't we

play08:49

can just throw an exception

play08:50

you can also do some different stuff

play08:51

here like i could change the user id to

play08:53

one

play08:56

and notice that the key will change a

play08:58

little bit

play08:59

let's say you were to change the user id

play09:00

to one but you didn't have the correct

play09:02

secret

play09:02

like this if i were to take this token

play09:05

and just go to my application and paste

play09:07

it in

play09:08

notice that when i click on my make a

play09:11

request button

play09:12

it's actually going to log me out and

play09:14

redirect me to the login page because

play09:16

again

play09:16

that token was bad right someone just

play09:19

tried to hack

play09:20

or spoof a token to our system and

play09:22

basically our application logged you out

play09:25

now the very last tidbit of information

play09:27

i want to talk about with the token

play09:29

is that the body and the header are

play09:30

basically just base 64 encoded

play09:33

strings okay so if you go to a base 64

play09:34

decoder and paste it in and click decode

play09:38

you'll notice that you just get back a

play09:40

json object here okay so there's nothing

play09:42

really like confusing or special about

play09:44

these two

play09:44

and you can see that they kind of

play09:46

decoded them for us over here

play09:48

it's mainly the signature over here

play09:49

which is just a hash um which

play09:52

that's for another lesson but go read up

play09:53

on what hashes is um just so we can use

play09:56

that to verify our token on the server

play09:58

all right so that basically wraps up my

play10:00

quick overview of jwt

play10:01

with node in express if you have any

play10:04

questions be sure to leave a comment

play10:05

below maybe i can come back and answer

play10:07

them

play10:07

give me a thumbs up if you enjoyed

play10:09

watching this video and like always if

play10:10

you're new to this channel be sure to

play10:11

click the subscribe button

play10:12

because i'm gonna have videos like this

play10:14

in the future that should hopefully help

play10:15

you become

play10:15

a better web developer all right thank

play10:17

you so much for watching have a good day

Rate This

5.0 / 5 (0 votes)

Related Tags
JWTNode.jsExpressAuthenticationWeb SecurityTutorialCodingAPIsCookiesMiddleware