JWT Authentication with Node.js, React, MySQL | Node JS Authentication With JSON Web Token
Summary
TLDRThis tutorial covers the implementation of JWT (JSON Web Tokens) for authentication in a Node.js application. After setting up the signup and login pages and storing user records in MySQL, the instructor demonstrates how to generate a token upon successful login, store it on the client-side, and use it for subsequent API requests to verify user authentication without requiring re-login. The video guides through installing JWT, creating a login route to generate tokens, storing tokens in local storage, and setting up a server-side route to verify tokens, ensuring a secure and efficient user authentication process.
Takeaways
- 😀 The video discusses implementing JWT (JSON Web Tokens) authentication with Node.js.
- 🔐 It follows up on previous videos that covered creating signup and login pages and saving records in a MySQL database.
- 🛠️ The first step is to install JSON Web Token on the server side using npm or yarn.
- 🗝️ JWT works by generating a token for the user upon successful login, which is then stored client-side.
- 👤 The token is used for subsequent API requests to verify the user's identity without needing to re-authenticate.
- 📈 The video provides an example of how JWT can simplify the process of requesting data like posts or comments after initial login.
- 💻 The server-side code demonstrates how to generate a token using JWT with a secret key and an expiration time.
- 🔄 After login, the token is sent back to the client and can be stored in local storage for future use.
- 🔑 The server includes a route to check user authentication by verifying the JWT token.
- 📱 On the front end, the token is sent with API requests in the headers to authenticate the user.
- 🔍 The video concludes with a demonstration of the authentication check, showing how the server responds differently based on token validity.
Q & A
What is JWT and how does it work?
-JWT stands for JSON Web Token. It is a compact, URL-safe means of representing claims to be transferred between two parties. The token is generated by the server after successful authentication and is stored on the client-side. Each time the user makes a request to an API, the token is sent to the server for verification. If the token matches the server's records, the server responds with the requested data.
Why is JWT preferred over session cookies for authentication?
-JWT is preferred over session cookies because it allows for stateless authentication, which is more scalable in distributed systems. It reduces the need for server storage and can be easily used across different domains and services.
What is the first step to implement JWT in a Node.js application?
-The first step to implement JWT in a Node.js application is to install the 'jsonwebtoken' package on the server side. This can be done using npm with the command 'npm install jsonwebtoken' or using yarn with 'yarn add jsonwebtoken'.
How is the JWT token generated in the Node.js server?
-In the Node.js server, after successful login verification, the server generates a JWT by using the 'jsonwebtoken' library. It takes the user's ID and a secret key, along with an expiration time, to create the token.
Where should the secret key for JWT be stored in a production environment?
-In a production environment, the secret key for JWT should be stored in an environment variable (e.g., in a .env file) to keep it secure and not hard-coded into the application's source code.
How long does a JWT token last in the given example?
-In the provided script, the JWT token is set to expire in 300 seconds, which is approximately five minutes.
How is the JWT token sent to the client-side in the application?
-After the token is generated on the server, it is returned as part of the response to the client-side. The client-side application then stores this token, typically in local storage.
What is the purpose of storing the JWT token in local storage on the client-side?
-Storing the JWT token in local storage allows the client-side application to easily access the token for subsequent requests to the server, ensuring that the user remains authenticated without needing to log in again.
How does the server verify the JWT token for subsequent API requests?
-The server verifies the JWT token by extracting it from the request headers, using the 'jsonwebtoken' library's verify method with the secret key. If the token is valid and not expired, the server processes the request; otherwise, it returns an error.
What happens if the JWT token is not provided or is invalid?
-If the JWT token is not provided or is invalid, the server responds with an error message indicating that a token is required or that the token is not authenticated.
How can the user check their authentication status using JWT in the front-end?
-In the front-end, a button is provided that, when clicked, sends a request to the server with the JWT token. The server then checks the token's validity and responds with the authentication status.
Outlines
🔐 Implementing JWT Authentication with Node.js
This paragraph introduces the topic of implementing JSON Web Token (JWT) authentication with Node.js. It mentions previous videos where the user's sign-up and login pages were created and saved to a MySQL database. The focus of this video is to demonstrate the use of JWT for authentication purposes. It explains the process of installing JWT on the server side using npm or yarn and how JWT works by generating a token for the user upon successful login, which is then stored on the client side. The token is used to authenticate the user for subsequent API requests without the need for re-authentication.
🛠 Generating JWT with a Secret Key
The paragraph explains the process of generating a JWT in a Node.js application. It emphasizes the importance of using a private key for JWT generation, which should be stored in a .env file for security. The script demonstrates how to generate a token with an expiration time of five minutes using the secret key. The token is then returned to the client-side upon successful login, along with a message indicating successful authentication. The paragraph also discusses how to handle the token on the client side, including storing it in local storage and using it for subsequent API requests.
📡 Creating an Authentication Route to Verify JWT
This section details the creation of an authentication route on the server side to verify JWTs. It describes how to extract the token from the request headers and verify it using the secret key. If the token is valid, the server responds with a message indicating successful authentication. The paragraph also covers the creation of a function to verify the JWT, which checks if the token is available and valid. If the token is not available or fails verification, an error message is returned. The function is then used as middleware to protect routes that require authentication.
🔄 Using JWT for API Requests and Authentication Checks
The final paragraph discusses how to use the JWT for making authenticated API requests from the client side. It explains how to store the token in local storage upon successful login and how to include the token in the headers of subsequent API requests. The server then uses the middleware to verify the token with each request, ensuring that the user is authenticated. The paragraph also includes a demonstration of how the authentication process works in practice, showing the server's response when the token is present and when it is missing, thus emphasizing the importance of JWT for secure and efficient user authentication.
Mindmap
Keywords
💡JWT
💡Node.js
💡Authentication
💡MySQL
💡Server-side
💡Client-side
💡Token
💡Middleware
💡Local Storage
💡.env file
💡API
Highlights
Introduction to implementing JWT authentication with Node.js
JWT is used for maintaining user sessions after login
JWT token is generated upon successful login and stored client-side
JWT token is sent with each API request for server verification
JWT eliminates the need for repeated logins for accessing different APIs
Installation of JSON Web Token package using npm or yarn
JWT is imported and used in the server-side code after successful login
A secret key is required for JWT which should be stored in an .env file in a real application
The token is generated with an expiration time, for example, 5 minutes
The generated JWT is returned to the client along with other login data
Front-end code handles the received JWT and stores it in local storage
A button is created on the front-end to check user authentication status
Backend API is set up to verify the JWT token
Middleware is created to verify the JWT token from the request headers
If the token is valid, the user's ID is passed to the next middleware
The front-end uses the stored JWT token to make authenticated API requests
A demonstration of how the system responds when the JWT token is missing
Conclusion and a call to action for viewers to subscribe and like the video
Transcripts
hi everyone this is a very important
topic in how to implement JWT
authentication with no.js in previous
video we created our sign up and also
the login pages and we saved the records
in my SQL database
and in this video we will Implement how
to use GWT with node.js okay in the
previous previous video we implemented
our sign up forum and we registered the
account and also we implemented our
login Forum okay and we checked that
whenever we logged in successfully we
should go to our home page okay so we
implemented it in the previous video so
for that video you have the link in the
description how to use it we use session
cookies and also saved registration and
also back check the login pages so we
did all this in the previous video so in
this video just use the gw2 or Json web
token how to use that okay so the first
thing is that we should install that in
our server side Okay so
so in this server side we will install
Json web token we will come here to the
terminal into the server side inside
here we will add NTM installed
Json Vapor token
if you are using yarn just yarn add Json
with token so I have already installed
that let's check it see Json web token I
have installed that okay so now let's
use that
so before starting let's check it how it
works okay how this this Json web token
works okay for example
um here is the user okay
the user logged into the system okay
this is the login
and they press the button
okay and it log into the server okay the
server
verified okay it login successfully okay
it generate a token for user
a generator token for the user okay it's
stored on the client side and this user
okay whenever the user again request to
an API okay to the server okay it
requests for example like a Facebook
okay whenever you log in you are
requesting for posts for comments for
your profile for something else so again
it should check that yeah so it we
should login again you whenever you are
requesting for example for posts okay
you need this should verify you is it
the user that you are logged in with us
or not are you authenticated with or not
either so it to can help with us to just
verify it based on the token okay this
is a user which is logging with us which
is verified with us which is
authenticated okay no need for again to
login uh back for the posts or comments
are for the profile so let's see just
the choker the token if that was uh
authenticated it means the token matched
with the server where there is the the
token it that match so no need again to
login for that uh API okay so let's see
for example there are money users okay
so it will check all the users so it
just shows the data the related to that
user okay so this is very strong
um the token is very strong okay so it
it is just simple when we are requesting
for other apis so it helps us um and it
authenticate the user that is it the
user that he is claiming or not so it is
all about that
so let's move now back
so to use that first of all we will come
to our server side code okay server side
okay here we are logging it to the
system okay this is the login route API
that we have written okay in the login
whenever we successfully logged into the
system okay so in the login system here
this is the code that we are plugging
successfully okay it means that our
password and username is correct so here
we will just use now gwg so first you
will import JWT so for that we will
write
import JWT from
Json web token after importing that
let's use it so whenever we logged in
successfully so here we will use that
now
okay so first of all we will just take
the ID from our records okay this one
the ID that we have okay we will just
take this ID so let's come here to our
code
and const ID is equal to the data we are
getting here okay this data this is in
our HIV that's okay whenever we run the
query we will get an array so we will
just take the 0 the first row and we
will take the idea of that after getting
the idea of that now we will use the GWT
foreign
[Music]
key this should be a private key okay
um in the real application that should
be in that EnV file okay you should have
a DOT EnV file in your startup site code
and you should store that there in check
from that eme file but now we are just
testing so I will just write something
like uh GWT if I just write like this or
secret key okay
secret key
and after that we will pass another
object so in that objective like we will
pass expires in for example expires in
like 300 okay it will just take around
five minutes okay so I thought so it
will generate a two conference okay
let's assign that to our variable
const token is equal to so this method
will just generate a token for us and we
will store that in the token variable
so after generating the token so now we
will just pass a return that is our
client said okay to our front end so to
return that instead of just forcing this
message we will just write
message
or I have it right let's assign
login true okay it means login is true
and also we will pass our token and also
we can pass
uh the data okay that will return okay
let me just simply fast that to our
front end so whenever we logged in
successfully we will generate a token
and we just pass that to our front end
so now let's move to our front-end site
code okay in let's come to the let's
uh let's come to the login to the front
end and here to the SRC to the login
in this league log in whenever we submit
our button this is the submission code
okay so we will pass this like in API in
our server side and here we will get the
results so whenever we succeeded but
right now we are not getting this
message we will get some
result
.data that
let's check it we will return this login
okay
data.login whenever we return on the
login if it was true so it will run this
code okay so we will come to this party
so just simply let's stick it okay that
we are returning okay we are going to
pack our home page or not let's check it
now let's come back and refresh it
and let's come in here enter the
password let's login Crystal login
button C yes correct
so whenever we come here so now we will
just so what you will do now with our
token so we will store our token in your
local storage okay it is a good way
maybe your yeah we will store that in a
local storage
so before storing that and the local
storage we will come here yes the user
interface we will create a button here
okay whenever we press that we will just
check is the user authenticated or not
okay by pressing that we will access the
for example user information okay so
whenever the user free starting that
button so we will check is
to access this information or not this
first of all create a button
yeah let's come here to the home page
just come here Yahoo
and here create a button inside this
uh check art okay
okay check out so now let's whenever we
click on this
on click let's add a class name to this
button button
primary
and whenever we press the this button so
we will call
let's create this function
um
yeah and the lot is equal to
it will create a function and here we
will call our backend API so for that I
will use axis
reported that has imported data
um just git okay and we will call
Sim Sim to this API this will be our
route
and let's assign it but instead of this
we will just check auth we will call
this route okay check out we will create
that later there okay so then we will
get a result
we will just cancel
log the result
cage if there was any error
console.log here
okay so we never replace this button we
will call this function inside that we
will just call this route and we will
check we will then display the result so
let's create this route okay let's come
here to the server and let's click that
here
he will just up that gate
in here cheek
okay same to that we will create a
like this
okay so after that we will get request
and response
we will just return
CDs are authenticated
so before running this route okay for
example we are passing this
authentication message to the front end
we will check is the user authenticated
or not so for that I will create another
function so I will name it verify JWT I
will create this function now and before
running this we will call this function
if that return result true so then we
will learn this otherwise not okay so
let's create that
Advanced verify GWT is equal to
we will create a function we will get
request response and that's your next
middleware
let's run that now
so here first of all we will get our
token from the headers okay we will
write counts token is equal to request
that leaders
[Music]
and from the edges we will get access
for example we will name it axis token
first we will get our token okay now we
will check if the token if the token was
not available okay
so then just return
s
we need
token
please provide it
or next time
okay else if the token was available so
then we will just verify it now
so so verify it will like GWT
dot verify
in inside the verify the first we will
then we will like our secret key okay
the key that we had before we assigned
before yeah this key okay we should
write it manually like this
it
okay so after that we will just edit a
function
there will be error or decoded
so if we get an error we will just
return result.json
not authenticated
okay else
we will just return
um first of all we will write like a
request dot user ID for example is equal
to decoded
decoded dot ID so it means that we are
passing our ID to the next route okay so
the next round to go further for the
next rounds so we will call next
uh middleware now
yeah so after writing this we did we
implemented it in our server side
so now let's move to our front end so
their whenever we get this response okay
first of all we should store our token
okay the token that we got in this login
we should store that and local storage
so let's come here and in the login so
whenever we log in successfully yeah
login successfully so we should store
that and the local storage local storage
that's it item
and we will name it token
and after that we will assign a result
the data
that token that we returned okay
the name of that was uh token okay so
let's check that
see the token that we return okay
so after that when we return the token
so we should
now use it
let's move to our
function that we created let's come here
yeah we were at the home page okay we
were at the home page so we said
whenever we click this button so we
would like to call this function so
after that we never recall this so we
should call this authentication okay
this API cheat auth okay we should call
this check out this one okay so we
should do uh pass our token also so here
we should pass with the headers at this
token okay that we used okay this one
access token we should pause this in the
heaters so let's write something like
this
heaters
and we will name it like this that we
did in our server cell okay access token
and we will pass our token to this local
storage that git item
the name of that was token
yeah everything is
working so now we will check that
so let's move to our front end so to run
this okay so first of all let's refresh
the page yeah let's log in okay after
logging so let's move to the console
what we are getting from our server side
okay let's to the console so let's press
this check out okay to check that let's
press it
see regard the result that authenticated
okay so if I remove the authentication
the token so let's come here to the
application let's come here local
storage and here let's remove this okay
let's delete it so let's come back to
the console
and let's press now this uh check out
okay so let's press it see we got we
need to please provide it for next time
okay it means there is no token with us
okay so it was the response that we got
from our server side
see if there was no token so please
provide it if that was verified so we
will get this result okay if that it
means that there was no error so we move
back to the next round so we got the
result that authenticated
so it was all about implementing uh JWT
in node.js so I hope this video was
helpful for you if you like this video
so please subscribe our YouTube channel
and also like this video on coming down
if you have any questions so please
comment down that thanks for watching
Посмотреть больше похожих видео
Learn JWT in 10 Minutes with Express, Node, and Cookie Parser
NestJs REST API with MongoDB #4 - Authentication, Login/Sign Up, assign JWT and more
#36 Spring Security Project Setup for JWT
#37 Spring Security | Generating JWT Token
Angular Login and Signup Page | Local-Storage | angular tutorial | angular tutorial for beginners
All about Firebase Authentication 🔥 | Login & Signup | Jetpack Compose
5.0 / 5 (0 votes)