Lecture thumbnail 0:00 / 0:00 The JWT tokens have some expiration date.
For example, we set it as 10 minutes.
So after 10 minutes, the token gets expired.
So at the time of validating that particular token,
the server denies the request.
So when that token is expired,
the user has to re-login in order to generate a new token.
But it will be practically difficult
to force the user to re-login
every time when the token is expired.
For example, if you ask the user to re-login
for every 5 minutes or 10 minutes,
as long as the user uses the particular web application,
it is very inconvenient to the user.
So to overcome this problem,
to enable automatic regeneration of the JWT token,
refresh tokens are introduced.
Generally, we will set a shorter span of time
for the JWT token in real-life applications.
For example, just a 1 minute.
So within 1 minute,
the user may make any number of requests
and those requests get processed normally.
But after that 1 minute of time,
the token gets expired, logically.
Then the browser should make a request
to refresh token API endpoint
in order to obtain a new JWT token.
See, first the user gets logged in
and then automatically
server generates two tokens this time.
That is the regular JWT token
that we have already generated
and also additional token
that is refresh token.
The refresh token is not a normal JWT token.
It doesn’t contain the header, payload, etc.
It is just a base 64 string of a random number.
So if you generate a cryptographic strong random number
and convert the same into a base 64 string
and that is called refresh token.
So now the browser has two tokens.
That is JWT token and refresh token.
As soon as the JWT token expires,
the browser makes another request
to an endpoint on the API server.
Hey API server,
take this refresh token
and if this token is valid,
please regenerate a new JWT token for me
because the older one got expired.
Then the API server verifies both tokens.
If both tokens are valid,
that means if refresh token is valid
at the same time the older JWT token is valid
but of course it is expired,
then it generates a new token
along with the existing refresh token.
In this way,
the refresh token acts as a proof of the user authenticity
indicating that the user is a valid user
and by verifying that refresh token,
the server would generate a new JWT token.
Let us try to implement the same practically.
First of all,
it is recommended to set a shorter span of time
for JWT expiration date.
For example, just one minute but not 10 minutes.
So after one minute of login,
the token gets expired.
Let’s run this application to see the same in effect.
Currently, I just try to login.
Currently, I don’t have a token in the local storage
and just click on login.
Yes, the login is successful and I have got the token
but after one minute of time,
the same gets expired.
It doesn’t mean that the token gets deleted
automatically or something happens in the client.
Only the thing is,
the expiration date that is set as a part of the token
gets completed.
So after one minute of time,
the token is no longer valid
so the server will reject the request if you make any.
You can refresh the page any number of times
and it is keep working
because the token is valid.
But if you try to make a request to the cities
after one minute of time,
actually still you are able to make a request to the cities
and we are getting the data
but the expected behavior is that
we should not be able to get the cities data
because of the time zone difference,
it may not be working right now
but the expected behavior is that
after one minute of time,
we should not be able to get the cities.
So then there is a need of refreshing
means creating a new JWT token
without needing to re-login
and that is what we are trying to implement
in this particular lecture.
Okay, let us try.
So in appsettings.json,
you have to mention the number of expiration minutes
for both JWT token as well as refresh token.
Already we have mentioned for JWT.
Let’s write one more,
that is refresh token
and I want the refresh token to be validated
for at least 10 minutes of time.
So we will set a shorter span of time for JWT
and longer span of time for refresh token,
maybe 10 minutes or more,
for example, maybe 60 minutes or something
which means that after 60 minutes of time only,
the user requires to re-login.
Now switch to the AuthenticationResponse.cs file.
Here we have already the properties for person name,
email and the token,
that is JWT token this time
and also we want an additional property
that is refresh token
and let the default value be empty.
Anyway, we will reset the same.
So we have a property called refresh token
that can be sent as a response to the client.
So when we have to create a refresh token,
it is when the user logs in or registers,
that means when the user is authenticated,
we have to create a new refresh token
and later based on that refresh token,
the JWT token has to be regenerated,
that is another story.
First of all,
we have to write the code for creating a refresh token
and storing the same in the users table.
If it is not stored in the AspNetUsers table,
we will be unable to validate the refresh token.
Means if someone has submitted something called refresh token,
how do you validate the same?
How do you verify that it is a legit refresh token
that is generated by the same server,
not by somebody else?
So that is the reason for one user,
only one refresh token
and the latest refresh token for the particular user
should be stored in the AspNetUsers table
in the same user account.
In order to store the refresh token
in the AspNetUsers table,
go to the identity models
and application user.cs file.
In this application user.cs file,
add a new property called refresh token.
So along the side of other properties
such as email, password, etc,
we are going to store refresh token also.
Since we made some changes to the application user class,
to reflect these changes back to the table,
we have to run the migration.
So go to the package manager console,
make sure you select infrastructure project
from the drop-down list
and run the command add migration
some suitable name,
for example, refresh token.
Add migration space refresh token.
So it has generated a refresh token migration
that will add a column called refresh token
into AspNetUsers table
with nvarchar of max.
In order to run that particular migration
in the same package manager console,
run the command update-database.
Okay, now you can expect the refresh token column
in the AspNetUsers table.
Expand your local DB,
your database is the cities database
and under this AspNetUsers table,
you can see the same.
Now it has a new column called refresh token.
That is fine.
Now we will be able to add the refresh token
for every user.
By default for all the users,
the values will be null.
See the refresh token value is null by default.
Anyway, when the user logs in,
we will store a new refresh token
in this particular column.
Okay, in order to generate a new refresh token,
we have to add a method in the JWT service.
And we can add it as a private method
because we want to call the same
as a part of the same JWT service itself,
not outside it.
So in the JwtService.cs file
in the services folder.
After that, create JWT token method.
Add a new private method.
Here, create a new byte array.
And we want 64 bytes array.
And by default, this array has its default value.
And you have a predefined class
called random number generator
in system.security.cryptography namespace.
So you import the same.
And it has a method called create.
So it creates a new instance
of the random number generator class.
It is not recommended to create a new object
for this class directly with a new keyword.
So we are following the recommended way.
So the purpose of this random number generator class
is that generating a random number
that is cryptographically strong
means avoids duplication.
And by using this particular instance,
you can call the method called getBytes
and supply the existing empty byte array.
So within this particular byte array,
it fills the random numbers,
means random values.
And after that, that particular random number
that is in the form of byte array
should be converted into base64 string.
And it can be returned.
So the return type is a string,
but it contains the base64 string of the bytes
and that bytes array contains the random number.
The base64 string of your random number
is a refresh token for us.
And then when you’re trying to return
the authentication response
after generation of the JWT token,
along with the token, email,
person name and other properties,
you can add an additional property
that is refresh token.
That is the property of the authentication response class.
Just before a moment, we added it.
And you can get the refresh token
by calling this generateRefreshToken method.
And that’s it.
So when you call this method,
it generates a new refresh token
based on this piece of the code.
And that gets added
as a part of the refresh token property here.
So you will get the same refresh token
back to the account controller
wherever you call it.
And in addition to that,
we have to store the same refresh token
into the AspNetUsers table.
So go to the account controller.
Go to the registration method.
Here within this post register method
in the account controller,
first we are trying to create a new user object,
inserting the same into the table.
And after that, we are signing in.
Then we are calling createToken method
of the JWT service
in order to generate a new JWT token.
And now this authentication response
includes with the refresh token as well.
Right?
So this particular refresh token
should be stored in the users table.
So it is as simple as,
hey, user object,
you have a property called refresh token, right?
So take this value.
Here, authenticationResponse.refreshToken
represents a new refresh token
that is generated as a part of the JWT service
and that is being stored
in the user.refreshToken property.
In order to update these changes
back to the database,
we have to call
userManager.update.
Update async of that particular user.
And not only that,
there should be some expiration date
or expiration time for refresh token as well.
So let’s set the same.
Already we have added expiration number of minutes
for the refresh token
in the appSettings.json file
so that in the authenticationResponse class,
add one more property that is
refreshTokenExpirationDate.
Expiration date time.
It is of date time data type.
No need to initialize anything.
So it contains the date and time
of refresh token expiration.
For example,
the refresh token is 1, 2, 3, 4 right now.
And this property contains the date and time
when that token expires.
OK.
Now switch to the JWT service.
So when you are going to return
the authenticationResponse class,
along with this newly generated refresh token
by calling this method,
you add additional property that is
refreshTokenExpirationDateTime.
That is,
from dateTime.now,
that is present time,
add number of minutes of
the value from the configuration.
That is,
under refresh token,
we have expiration underscore minutes.
I mean this value over there.
And we have to convert the same into number.
For example,
this value is represented as gem.
So it returns the date time
after 10 minutes from now.
That is the meaning of this code.
And this is being returned
as a part of the createJWTToken method.
And now we can read that value
in the account controller.
So switch to the account controller.
When you call this createJWTToken,
we are getting both values,
refreshToken as well as
refreshTokenExpirationDate.
I mean refreshTokenExpirationDateTime.
But we have to also store the same in the database.
So let’s comment this particular line of code.
Go to the application user class.
Add one more property here.
refreshTokenExpirationDateTime,
which is of date time data type.
And you have to run the migration one more time.
So package manager console.
Make sure you selected infrastructure project over here.
Add migration.
refreshTokenExpiration.
Some meaningful name for the migration.
If you have any compilation errors,
you have to fix them first.
Then run the same command update-database.
So it adds that refreshTokenExpiration column
in the table.
Now switch to the application user class.
Go to the account controller.
Now you are able to store the same in the property.
So hey user object.
I mean it represents a particular row
in the AspNetUsers table.
The refreshTokenExpirationDateTime
equal to this particular value.
And we will update the same in the table.
That’s all.
So we have generated a refresh token
and we set an expiration date time for the same.
That is fine.
And we will give the same
as a part of the response
through this return OK response.
And on the client side,
we have to store the same in the local storage.
To do so,
go to the registerComponent.ts file.
We are already storing the token.
I mean JWT token in the same way.
Store one more.
That is refreshToken.
From the response,
you can read the refresh token.
Do exactly the same thing
in the login time also.
So go to the loginComponent.ts file.
Here in the submit button click method.
I mean login submitted method.
Here also store the refresh token value
in the local storage.
Now run and check this application.
Let me clear this old token.
By clicking on this clear all button over here.
Under application tab,
clear.
Now enter the valid values.
Login.
Ignore this error message
since I am using a common
Harsha123 password.
So it was found in the data bridge online.
So just ignore the same.
It is not a serious password though.
But the point is,
now we are able to see two tokens
One is the JWT token
which contains the header, payload
as well as signature
as we have discussed earlier.
And also a refresh token.
The refresh token is comparatively shorter.
It is just a base64 string of random numbers.
I mean just random bytes.
OK, we have added this code
only in the registration method.
But we have not added the same in the login.
So carefully select these few lines of code.
Go to the post login method.
In the post login also.
After successful password login.
We are getting an user object.
And after successful sign in.
And also after successful creation of the token.
Here you can paste the same.
We are getting the refresh token
from the authentication response.
Which you got by calling this
create JWT token method.
And we are storing the refresh token
and its expiration date and time in the table.
And updating the same changes back to the database
by using user manager.
So build the solution and run the application.
You try to relogin the same.
I am just trying to clear
this particular application tab.
Local storage is empty now.
Login.
Yes, now we have got two tokens.
That is the regular JWT token.
As well as refresh token.
And also this refresh token must be stored
in the table, isn’t it?
So go and check the AspNetUsers table there.
Right click on AspNetUsers table.
View data.
Now within this particular user where you logged in.
You can see the value of refresh token.
And it contains the refresh token.
The same one which we have generated programmatically.
And refresh token expiration date and time as well.
So next time we can validate the refresh token
based on this database data.
That means next time when the browser
submits the refresh token to generate a new JWT token.
We can validate or verify that particular refresh token
with this database data.
If they match then only we can say it’s valid token
otherwise invalid token.
Because there is no any cryptographic way
to verify whether this token is valid or invalid.
Because it is just a random bytes.
That is why we have to store the refresh token
of the particular user in the same user account
in the table.
Okay, so far we are able to generate the refresh token.
And we can set the expiration date for the same.
And we are able to give the same back to the client.
And in the client we are storing the same
in the local storage.
But the next part of the process is
based on this refresh token we should be in a position
to regenerate the JWT token.
Of course only when it is valid.
We will try to implement the same in the next part.
Play Play Play Play Play Play Play Play Play Stop Play Start Start Start