Learn JWT in 10 Minutes with Express, Node, and Cookie Parser
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
🔐 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.
🛠 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.
📚 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
💡Node.js
💡Express
💡Authentication
💡Secret Key
💡Middleware
💡Cookie
💡Environment Variable
💡Expiration
💡HTTP Only Cookie
💡Base64 Encoding
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
hey everyone i hope you guys are having
a great day welcome back to another
webdav junkie video and so in this video
i want to give you a five minute
overview
of how you can use jwt with an example
of using a node in express
but you can take these ideas and apply
to whatever language you want like
python and django php and laravel but
let's just dive into it to save some
time
right here i have a server.js file which
is hosting in express application
and the main thing i want to talk about
in this app is we have a url
called slash login and we also have a
url called slash add
but these are the main things we're
going to focus on but just to kind of
make sure you're not in the dark we do
have two static files that are hosted we
have an index file
that is located here that has a form and
a login button
and then we have a welcome page which
also has a button that just makes
a really basic request to the ad page
and then finally we have a cookie parser
set up
so that we can take the jwt and put it
in the user's cookie so we have a login
form here and we are going to hit that
login endpoint so i do have a
test username typed in and a password
typed in and so when i click on login i
want to show you what kind of happens
so it's going to hit this express
service and it's going to go to this
login route okay so inside of my routes
folder i have a login
file and let me just walk you through
this code real quick we are basically
including a json web
token package or library which allows us
to sign and verify jwt tokens and
this is the end point that we're hitting
and to kind of walk you through this
really quick
we grab the username and password that
came over the payload
we checked in the database for that user
based on the email they provided or
username they provided
and then we verify is the password
that's stored in the database
matching the one that the user sent in
in the login page if it's not we just go
ahead and throw an error back
but the important part of this whole
endpoint is the
signing process so we have a jwp.sine
function call here
and we are taking that user object that
we got back from the database
and we are just signing it okay so what
that means is it takes an object
and it basically will look at
the payload and it'll create a hash and
put it
as a signature at the end of the jwt and
we'll we'll talk about this at near the
end of the video of how a jwp is
composed but a second important part to
point out is that we have to provide a
secret here so you notice here we have
processing be my secret
so when i host my server this is
actually set to
i think hello so let me refresh this
yeah so this is an environment variable
that i set to hello here
and that is what we're using to sign our
jwt this is important because
this prevents anyone else out there from
just creating jwts
and hitting your server to try to access
it right they have to know the exact
same password that your server used
in order to create a jwt token to uh
hit your endpoint and then the third
thing that's really important to talk
about is
the expires in property here so usually
jwt tokens
have an expiration date and the shorter
they are the
more secure the safer i'm just going to
do one hour here to kind of show you but
typically you want to do like 15 minutes
10 minutes 30 minutes
um and so we create this token and that
is what we can use as kind of like the
key
that the user can use to hit our
endpoints and we can verify that hey is
this user actually the correct user uh
so after we have the token
we are going to set a cookie on the
response header so that the browser can
actually say hey
i have a cookie i need to set in my
browser and keep track of it
and then later on the browser will send
that cookie when it does for
future requests uh some things i want to
point out here is it's
usually most safe to use an http only
cookie
there's also some other flags that you
can look into if you want to make this
more secure
but i'm not going to do that in this
example and then we redirect them to a
welcome page so let's just go back here
and click that login button
the first thing i want to show you is we
hit that login endpoint here
and we are doing a post request to that
endpoint but the important part is that
the response comes back
with a set cookie in the header right so
this is that token that we're talking
about
and the server told our browser that we
need to set that cookie
so to further exemplify that let's click
on this application tab
and let's go down here to storage where
it says cookies
and click on our url so you'll notice
that the cookie is actually set
with this token keyword and we have the
cookie or we have the jwt token here
right we're going to talk about the
token
uh in just a bit like what this actually
is because it looks like a
random jumble of characters but just
know that whenever we make a
future request that token is going to be
put
onto a header so let's further check
this out we have a button here on the
welcome page which just does a post
request to that slash
add in point okay so before i click it
let's go back to our server notice that
we have an ad in point
but the main difference with this route
is that we do have some middleware set
up to make sure that the cookie is
provided so
this is like a secured route we don't
want anyone just hitting this endpoint
we want someone who is authenticated
and we want to maybe check their user id
to do some logic
so before we do the logic we're going to
use this middleware function to
basically take the token out of the
cookie
and verify it all right so here we are
saying get the token
based on that token key that we talked
about here
get the token out of the cookie and then
we verify it okay so this is
a library function call we can do
basically passes a token
then we also pass it that secret key
that we talked about earlier
that we used for signing the token and
if the token that came in
has the exact same key in the signature
as the one that is set here then this
will just work it'll return the
decoded token to us which happens to be
that user that we sign here
and then we can access things that we
put on that right so for example the
user id
but in this middleware i'm just going to
set it on my request and call next which
will allow us to go to the next step
in the route endpoint which happens to
be this ad route
which will just basically redirect us to
a welcome page
so let me just go ahead and click that
and show you
so notice here it did a request to the
add page again that
that cookie was set in the header here
we have that cookie here
and the server basically took that
cookie verified it
and called the next um step in the
process which is redirect to welcome
and notice that we also got a request to
welcome because our browser was
redirected to it let's talk about the
other scenario where the token is
invalid or the token was expired okay so
let's go back
to our login and let's make this expire
after one second
so now if i were to go back and kind of
clear out my
cookie here and go back to the login
page
if i were to type in that same stuff so
notice that when i log in we still get
that cookie but
now since it expires after one second if
i make this request here it's actually
going to take this
else path which is going to clear the
cookie for us automatically
and redirect us back to the login page
let's just go ahead and click that and
you'll notice that the cookie
is removed from the cookie section here
we don't know
we don't ever have a token and we are
back at the login page so that is my
like
um invalidation logic setup uh and i
think that's about it so let's change
the
the expires back to an hour the last
thing i want to show you all though
which is kind of important is like what
is a jwt token like what is it made up
of
so what i'm going to do here is i'm
going to make another token
let's just go ahead and grab that jwt
token and i want to paste it into a
website
called jwt dot io alright so if you go
to jwt io
and go to this debugger section you can
actually paste in your token and what
this does is it's going to
split apart your token into the various
parts and kind of show you what it's
made up of so
every token usually has a header section
which is this red section
it has your payload or your body which
is the purple section
and then it has a signature okay so this
signature
is created using that secret key that we
set in our server
and then also with the header and the
payload so basically takes the header
and the payload
and the secret creates a hash and it
puts that at the end of your jwt token
again this allows us to basically verify
that any token that comes to our server
has the exact same hash that we expect
because we are the ones who know
how to sign and verify tokens with that
secret key
what you can do here is if you were to
paste in some random stuff like
i'll just type in some random characters
and paste our existing token
notice down here it says invalid
signature
but if i were to put hello
and replace our signature notice that it
says signature verified so this is
basically the same steps our server
server's taking it's just using this
secret string of hello
and making sure that this is token was
actually issued by myself
by my own processes and if it wasn't we
can just throw an exception
you can also do some different stuff
here like i could change the user id to
one
and notice that the key will change a
little bit
let's say you were to change the user id
to one but you didn't have the correct
secret
like this if i were to take this token
and just go to my application and paste
it in
notice that when i click on my make a
request button
it's actually going to log me out and
redirect me to the login page because
again
that token was bad right someone just
tried to hack
or spoof a token to our system and
basically our application logged you out
now the very last tidbit of information
i want to talk about with the token
is that the body and the header are
basically just base 64 encoded
strings okay so if you go to a base 64
decoder and paste it in and click decode
you'll notice that you just get back a
json object here okay so there's nothing
really like confusing or special about
these two
and you can see that they kind of
decoded them for us over here
it's mainly the signature over here
which is just a hash um which
that's for another lesson but go read up
on what hashes is um just so we can use
that to verify our token on the server
all right so that basically wraps up my
quick overview of jwt
with node in express if you have any
questions be sure to leave a comment
below maybe i can come back and answer
them
give me a thumbs up if you enjoyed
watching this video and like always if
you're new to this channel be sure to
click the subscribe button
because i'm gonna have videos like this
in the future that should hopefully help
you become
a better web developer all right thank
you so much for watching have a good day
関連動画をさらに表示
#37 Spring Security | Generating JWT Token
JWT Authentication with Node.js, React, MySQL | Node JS Authentication With JSON Web Token
#38 Spring Security | Validating JWT Token
Oauth2 JWT Interview Questions and Answers | Grant types, Scope, Access Token, Claims | Code Decode
#36 Spring Security Project Setup for JWT
NestJs REST API with MongoDB #4 - Authentication, Login/Sign Up, assign JWT and more
5.0 / 5 (0 votes)