Transcripts
1. INTRODUCTION: Welcome to the
ultimate JWT course. In this class, we
are going to learn JWT in easy and simple language. After completing this course, you have proper understanding
of JSON Web Tokens. So first of all, we
are going to see what is JWT, why we need it. After that, we will start
with back-end part of JWT, which is how to generate tokens, how to verify tokens, and implement the security
API just for logged in users. After that, we will move to front end part in which we
store Dogan in our browser. Implementing Sign-up login
and logout features, sending token in the header and create component
for private route. In Project section, you will get all resources
for this class. I'm very excited for this
class and hope you are too. Let's get started.
2. What is JWT & Why we need it?: So JWT stands for
JSON web token, which is used to
securely transfer information between two parties, like back-end and front-end. But the main reason
for using JWT is to authenticate user
with using its token. Let's understand this
with the example. Here is hardly a login with his account information,
email, and password. Now our server plus
j, the inflammation. And if it's true, then server returns
it user ID as a response and store that
in the citizen or cookie. Now whenever he sends the request some
secure information, let's say all his
bank information. Server post asked
for the user ID. And if he has user ID, then and then server sends
the secure information. But here one big problem, this isn't our cookie in
which we store our user ID. It can be easily
modify in the browser. Let's say I just changed this user ID to
someone else user ID. Then we get the information
about that user. So this approach is not secured. Now to solve this issue, we introduced JSON web token. Now hardly again login with
his email and password. Now our server paused to
check the inflammation. And if it's true, then server returns
the encrypted unique token and store that
in the local storage. Now the great thing about
this token is it is made with user details and one secret key which we defined on server. So whenever hardly sends a request to policy
current information, then server post
asked for JWT token, verify it using our secret key. If it's verified, then and then service and that
seeker information. And if we change anything in user information than
our token will change. So that's why we use JWT,
user authentication. I know you have many questions
related to JSON web token, but watch this full tutorial, it will clear your doubts. In this tutorial, I'm
going to use NodeJS as a backend and React
JS for the front end. But you can still follow these no matter which
programming language you use.
3. Starting With Backend: Here I create one
simple project in Node.JS in which post I connect this node server with
my localhost MongoDB database and listen this server
on localhost by thousand. By the way, you can also
download the starter code. Let's first install all
dependencies for this project. So open terminal and
write npm install. Let it run in the background. Now in models folder, I created one model user
with only three pills, name, e-mail, and password. Now in the route folder, I define all routes. The bus route is for user registration in
this users.js file. So here, first we get all data from request dot body
and destructure it. Then we check for existing user. And after that, we will save
the user information in the database and Sandy
user's information as it responds
pretty simple route. Then in server.js file, I import this user
out and define this route pad as
APIs less user. So open up ten minute
and write Norman server. This will continuously
update server on Jane's. Great, we get
database connected. So let's taste is with Postman. Now I pass our route here
and select row and Jason. Now here I pass data
object and click on Send and see we get user data. Now, if B again click
on Send button, then we get user already exist. So that's the little
introduction for who is watching node pause time
just for understanding. Similarly, we have another
route called odd for login. Let me directly show
you in Postman. So I pass correct
email and password. Then click on Send. See, we get current user. But if we pass wrong password, then we get error. Now there are three main
task for JWT in back-end. Watched. One is generate
token on register. Second, Generate token on Login. And last, when user asks
for security information, we have to verify token. Let's start with
task number one.
4. Generating JWT Token on Registration & Login: So open terminal and add new
terminal and write npm I, JSON Web Token and hit Enter. Now user out. At the top I declare JWT equals two required and
decent web token. Now after we store
data on registration, reason the JWT Token
or JWT dot sign. Now first argument is our data which we want
to pass with this token. So I create a new
variable called JWT data because to underscore ID user dot underscore id
comma name, user.name. Now pass this JWT data here. Now the second parameter
is our JWT secret key. So we can pass here any string like code bless
you, or whatever. This secret key is very
important for authentication. In this case, it's not secured. So we will declare
our secret key in dot ENV file right here. Jwt secret equals to anything like 123 code blast or something which
will not easily guess. Like if you are
creating Zomato app, secret key is like
Zwicky is the best. Now save it and back
to our user route. By here we add processed
dot ENV, JWT secret. With this process dot ENV, we can access variable
of this ENV file. Now, if you want to expire
token in some time, then we can also define that. So I want to expire
this token into hours. So if a user buys this
token after two hours, they how to log in again
for new token, right? In object expires in
and in double quotes. You can write time. If you want to export it
in one day, then pass 1D. But I pass here to
wet or two hours. Again telling you
this is optional. Now store this in a variable called token in the response, send token, save the changes. Now in postmen, we
create a new user code to read gmail.com
and click on Send. See, we get this
encrypted token. Now copy this token
and header to JWT.io. This is the official
site of JWT. You can read here
it's documentation. Now click on this debugger. Yeah, we can decode our token. Now let's understand what inside this token based our token here. Now, all tokens divided
into three parts. First part is about header, which is in red color. Second part is about payload, which is in purple. And last and most important
part is signature, which is in blue color. Now this header contains the
algorithm and token type, which is very common. Don't focus on that.
Now this payload contains the data which we
want to pass this token. In our case, we
pass ID and name. See, here we get our data. So we can display that data on our front-end without
requests for new API. And we have more data, which stands for issued at the value is time when
our token generated. And EXP is our exploration time. Now the last part, signature, which is generated
based on our header, this payload data
and secret key, which is only
available on server. So this will prevent
users from getting their own Dogan
and then modify it with ID to pretend
to be someone else. Because if you modify anything
in this payload or header, then the signature
will regenerate it. There are no chance for user
to do something unethical. So that's why JWT is so popular. So we successfully created our JSON Web Token
Board register. Now let's do the same for login. So copy these three
lines and go to ahd dot js file and paste it here. And at the top, redeclare JWT equals to require JSON Web
Token and save it. Now in login, high-pass
correct data and send it. See, we get token. We successfully complete
or second task or backend.
5. Verifying token on secured route: Now the last task, which is venues or request secured route, which means that data is only accessible by
logged in users. Then we have to pause to
verify the JSON Web Token. And if it's valid, then we return data. So in users.js file, we add new API, getting the current logged
in user information, which will display
on bra palpate. So right router dot
get Les Paul path and add a function with
the request response. Now, we need to create
our middleware in which we verify token
on every secured route. So create a new folder
called middleware. And inside it, we create
new file called ab.js. Great. Now here we first define
the function and add module.exports or
export this function. Now you might know our
middleware function has three parameters, request, response and next one. Now, let's not worry about this. Now inside this,
we first pass the token which you pass
through header. So request header and
pass here header name, I pass x or token, which is commonly used name. You can pass whatever you want to store this in token variable. After that, we will check
if token is not available. Then return response
dot status for 01, Dotson, and bass, access denied. Dogan not found. And if token is available, then we verify it. So at the top, redeclare JWT equals to require
JSON web token. Now here we write
JWT dot verify. Now the first parameter
is our token, which we want to verify. The second parameter
is our JWT secret key. So right, process
dot ENV, JWT secret. Now this will give
us id and name, which we pass earlier. So let's store this
in variable user, and we pass that values in request dot user equals to user. After that, we will
call the next function. So it will run the API. Now, if this token is valid, then this code will
give us error. Soviet try and catch
block for that. Now, move this inside try block. Now in this catch block, we write response
dot status, 400. Dots send invalid
token and save it. Now back to users.js route. And first we import odd. So write const odd equals two, required double dot slash
middleware, less odd. Now we pass this odd
middleware here. So when someone called this API, this odd middleware will run. And if token is verified, then, and then this
function will run. Now right away IT
User dot find by ID and password request dot
user dot underscore ID, which we declared in
autumn middleware, and store it in a
variable called profile. Then response dots and profile. Here we add a weight. Therefore, we have to
write here async, Save it. Now let's test this private API. So back to Postman and
add new request and pass here http colon
double slash local host, colon Python slash
api slash user, and click on Send. See, we get the
error message access denied because we haven't
passed token in header. So go to Header section. And here is x odd token, which we pass in
autumn middleware. And here we pass our token. So I copy this token from login, taste and paste it here. Now click on send and we
get the user profile. Now, if we change anything
in this token and send it, then we will get invalid token. So our back-end part
is completed here. Minimize this server via score because we need to
keep running this server. Now we will see how to
handle JWT in React.
6. Starting Frontend Authentication: So here I opened the client
folder in another VS Code. First of all, we will
install all dependencies. So open up and write npm install and let
it run in background. Let me give you a quick overview of this React application. So in this app component, I create one now bar, and inside the snail bad, I create three now links. And for routing, I create this routing
component in which I define all routes like home, login and register,
simple as that. Let's run this application. So open up a terminal
and write npm start and hit Enter C. This
is our home component. After that, we have login
form on login page. So if we write email and password and then
submit the form, we get values in console. Similar to this, we
have registration form. We fill the form and
click on Register button. Then we get values in
console, so forth, JWT, when you use a resistor, we send token from
the back-end, right? So after that, we store that
token in local storage of browser and pass that token when we making
any secure API request. In our example, our profile API. So similar to backend, we have three tasks
for front-end. First one is we store
token on resistor. Second we store token on Login. And last, we said
token to our header. So we can make
secure API request.
7. Storing Token on Register & Login: So open up terminal and add new terminal and write
npm I SEOs and hit Enter. If you don't know SCOs, your inject my XES guide video. Now I create a new
folder called utils for utilities and create a new
file with the name STDP ab.js. Now in this file, first of all, I import from zeros. And after that, I create one variable called instance
equals to XES dot create. Now pass object and inside
it, rewrite base URL. Here. We can pass our
backend base URL, which is http colon double slash local host colon by
thousand less API. And at the end, export
default instance. So basically we create a
shortcut for making API request. So we don't need to write
every time full URL. If we make request
or localhost colon pi thousand slash
api slash user, then we have to just
write slash user. Now go to component folder register and open this
register dot js file. So this is a registration form. Now in submit function, we will call our register API. So at the top, first
import STDP from, we go to holders up and
add details as GDP. Now I remove this console
right here, http dot post. Now the first parameter
is the path of our API, which is less user. And second parameter
is user details. Now this statement
returns a promise. Let's handle this
with async await. I write here of eight, and here we pass AC. Now let's store this value in
a variable called response. And console this response, save the changes
and take a look, go to resistors and paste and fill the data
with unique email. And click on Register button. See, we get this
response object. So in this data, we get our token. Let's distracter this response and get this data property. Now, let's do our token
in our local storage. So our browser has their
own small storage. So we write local
storage, dot set item. Now the post variable is the name of this
field, which is token. And second, we pass data, which is actual token. And after that, we will
move user to homepage. For navigation. We use React router dom. At the top. I important use navigate from React router dom,
end right here. Let navigate equals
to use navigate. And after this, we
write navigate. And inside it, we pass our path, which is less sales
attendees, and take a look. Now pass different e-mail and
click on Register button. See we redirect to homepage. Let me show you where
we store our token. So go to Application
panel over here. Now click on local stories
and select your web URL. See, restored our token here. Now back to registers
and palm and buys the same data and
click on Register. In console, we get error. So back to our
React application. And we add try-catch
block for handling this error mode discord into this try block,
engage block. We will simply console this era, save the changes,
and take a look. Click on Register button. See, we get the adder object. Now in this error response, we get our data, which we send from back-end
user already exists. So we write here if
adder dot response is available and then adder dot response.status
equals to 400. Then set error, adder
dot response.data, which is our state variable. Because we don't want to show any other adder which we
don't send from backend. And at the bottom, I already add the condition, which is if adder is available, then print that error, changes and take a look. Now I click on this
Register button and we get this era now similar
to our login page. So I copy this try and catch block and open
login dot js page. And in the handle submit
function, paste it. Now copy this to imports and
paste it in login component. Now copy this last navigation
line and paste it. So now here we change
the path from user, do odd and buys this form data, which is also user details. The attendees, and take a look. Now fill this form with
the wrong information and see we get our adder now
past the right information. And z really direct
to home component. And you can also check tokens
stored in local storage.
8. Getting User Information From Token: Now I don't want to show
this login and register link if a user is
already logged in. So back to Add Component, we create one state
variable called user and initial value to null. And at the top, import
used it from React. Now the logic is when
these users date is null, which means user
is not logged in. User is available, then
user is logged in. The question is, how we can
get the current user data. Remember, we pass our user data into our JWT payload section. So we use that data
here for authenticate. Now we add here condition. If in local storage
we have token, then we get data
from token, right? If local storage dot
token is available, then change user state. Now how we can decode
our token and get that data so that we have one
library called JWT decode. So open up terminal
and write npm I JWT dash d code and hit Enter
and close this terminal. Now here we import JWT
decode from JWT decor. Now inside this IV, we get first token
from local storage, dot get item and token. And now we use JWT decor. And inside this, we
pass this JWT token. Now store this in variable log user and
set user to log user. Now, let's console this
user state variable. Save the changes, and take
a look and we get error, which is because
of infinite loop. Let me explain you here. First, we check for token and we said user data to
this user variable, which creates in finite loop. So we have to move this code outside of this app component. Now remove this set user
function and direct path this log user value
as initial value. Now before this if condition, redefine this log user variable because if token
is not available, then we can't access this log is a variable and remove
this constant also. Now save the changes
and take a look. See, we get our user details. Now using this user variable, we will display private links and height days login
and register link. So past this user as prompts
in this Navbar component. Now in now by component, 3D structure props and
get user variable. Now we've grabbed these two
nav links with condition, which is if the user
is not available, then so this links. Now we have to pass
here, react pregnant. And after that, if a
user is available, we will show two more links, profile and log out. So I duplicate this block and Jane's condition and
post link per profile. And second for logout
changes and take a look. See, we get our profile
and logout links. Now go to Application panel and select this token and remove it. What tasting purpose. Now refresh the page. We get login and register links.
9. Fixing the Refresh Bug: Right now, you think our
application is running well, but we have bug here. Let me show you. So open login form and the
right email and password. Now click on this login button. Now to press the
local storage C, we get our token. But these links
are still visible. Because in app component, this if condition
only run one time. So if we manually
refresh the page, then we get other links. So after login, we have to automatically
refresh the page. It's very simple. So back to our login component. And the mood is
navigate an ad here, window dot location equals to. Now remove this used navigate. And also remove from important, save this and copy this window.location and pasted
into register component. A mode is used. Navigate and also remove, save the changes
and take a look. Now again, remote token
and refresh the page. Now filter email and password. Then click on Login. See we get our links
without manually refresh. Perfect.
10. Implementing Logout Feature: Now let's create components. What these two pages
in components folder. I create a new folder
called profile, and inside it create a
new file, profile dot js. Now write AFC,
React boilerplate, and I pass here H1. This is profile component. Save it. And let's create a new
folder called logout. And inside it, create a
new file, logout dot js. And again, write our AFC
boilerplate and save this. Now go to routing dot js file. Here we define our routes. So duplicate these two
lines and genes but to profile and
element also profile. And for second route, we change bad to log out. An element also log out the
changes and take a look. See, we get our routes. Now, let's first complete
the logout feature. So open logout dot js file. So logout is basically removing the token
from local storage. That's it. So I imported use
effect from React. And here I create, use the back arrow function and empty array because we only
want to run this one time. Now inside this
using local storage, dot remove item, token. And after that, we will
redirect to home base. So right, window dot
location equals 2s. Let's save it and take a look. Now click on logout and see
we successfully logged out. Now let's login again. And see, it works well.
11. Making Secured API Request with Token: Now in this profile page, we want to display
user information that we have GET request user. Let's open profile dot js file. And first we import
the use effect. And after that, we
import STDP from Vigo to Fuller's up
utils less STDP. Now in component, we declare one function called get user
profile, arrow function. And inside it, we
patched data, right? Http dot get slash user. Now let's add a weight. And for that we have to add a C. Great. Now let's store this
in variable called response and consult
the response. Now let's create a user object. And inside it we
call this function. Save the changes and the color. Go to profile page
and see we get error, which is Unauthorized because
of our odd middleware, which were declared in backend. Only that user can access this information who
sends token in header. So let's solve this issue. So for that, we
create new file in your tales called
set or token dot js. Now create a function
called set or token. And bars here, token. Now inside it, we write
if Dogan is available, then we pass this token
in header by using x. Use. So important from our STDP pile, this is very important step. Right here. X equals dot defaults
dot header dot common. In square bracket. We pass our header
name, which is x, or token, which we set in our
back-end, equals to token. Now in as, read, write, delete, and then copy
and paste this command. And let's export
default, set or token. Now let's call this
function app component. So far most important set or token from utils,
less set octagon. Now, after we store
this token in JWT token and pass our
token, which is JWT. Save the changes and
refresh the profile page. See we get data of profile. So that's how you can
pass token in header. Now you don't need to write
header for all requests. This set or token
will do that for you.
12. Creating Private Route Component: Now let's take this
application more advance. Because here I found one bug. So let's logout and in the URL, add slash profile and hit Enter. See. Here we get the profile
component which is only accessible by
authenticate user. Although they can get any data because of
our security API, but it's not a good practice. So if user without login, I do, I enter in the space. We will redirect the
user to login page. So let's create a new file in doubting folder
called private route. Now right, RFC quad boilerplate
and rewritten here. If user is available, ventral outlet, which will help us to
display a child component. I will show you that
in just a second. If user is not available, then navigate to slash login. Make sure to import outlet and navigate from React router dom. We get user from props. So back to App component. And in this routing component, we pass user equals to user. And in routing component,
3D structure user. Now in React router version six, we can define private
routes very easily. This private route
is nothing but just a function
which will redirect user if they have not logged in. So right route and don't pass path directly element
and pass here private route
component with user equals to user and
closest route. Now, in-between this route, we can pass all our
private routes. So let's move this
profile and logout grout. So this basically means whenever someone tried to route
any of these routes, then these private route
function will run post, save the changes,
and take a look. See, we directly
move to login page.
13. Fixing the small bugs: Now login with your
information in the URL types less
login and hit Enter. See, we get this login form. So let's fix this
real quick. Here. Who buys these user
login component? Now open this login component
and destructor props user. After that, we write here use effect and error function
with an empty array. And inside this, we check
if user is available. Then we send user one step back. Let's import user from React and important use navigate
from React, router dom. And after you state, we add lead navigate
equals to use navigate. Now right here, navigate
and pass minus one, which means one step back. It works like Back
button in browser. If we write minus two, then it will go two steps back. Save this, and take a look. Now type here, it's
less login and enter. See, we redirect to homepage. Now let's copy this from login dot js file and paste
it inside register component. Now again copy this input
lines and paste it at the top. Now go back to
routing component and pass user equals to user. Whereas this third component
and in register component, 3D structure user in drops
the changes and take a look. See, when we tried to
hit Register page, we redirect one step back. So congratulations,
you've successfully create user
authentication using JWT, which is the most used way to authentic user applications. I hope you learn a lot
from this tutorial. If you have some doubts, you're going to ask me
in the comments section. See you in the next video. Have a nice day.