Lecture thumbnail 0:00 / 0:00 In this lecture, let us write actual code for generating JWT token and sending the same as a part of
the response to the client.
In order to generate the JWT token, you need not write your own explicit code for generating the base64
string or hash.
The same is internally done by a NuGet package called Microsoft ASP.Net Core Authentication dot js bearer,
and you require to install that package wherever you would like to generate the token.
But instead of writing the JWT generation code directly in the controller, I would like to write the
same as a reusable method in a service.
And that service definitions are placed in the core project, right?
So in the core project you have to install that NuGet package.
So right click on dependencies of Core Project.
Manage NuGet packages.
Browse.
So select this package Microsoft ASP.Net core Dot authentication JWT bearer and select the same version
as of me that is 7.0.4 and install.
And okay, so that package got installed in this core project, as you can see here.
Let’s try to define a DTO model class that represents the data that you want to provide to the client.
As response means after generating the token, you have to include the person name, email, and along
with the token to send as response.
Let’s call it as authentication response.
Let’s create that model class.
Right click on DTO folder in the core project.
Add new item code class file name is authentication response.
So we have authentication response file.
Create the properties person name email.
And then the token.
The token is also represented as a string.
Finally.
So keep the data type as it is.
Optionally initialize the same.
Anyway we will try to initialize the value later.
And then expiration time.
Okay.
These are the properties that I would like to include as a part of the response.
After successful login, let me create a service.
Contract means an interface.
Right click on the core project.
Add new folder.
Folder name is service contracts.
Right click on service contracts.
Add new item.
Class I jwt service.
It is name of our user defined service.
And create a public interface.
In this I would like to have only one method.
Return type is authentication response class that we have created before.
A moment.
Import the corresponding namespace that is DTO.
Name of the method can be anything.
For example create JWT token.
So here the idea is if you supply an application user object based on the existing user details, it
has to automatically generate the JWT token and return the same as a part of this authentication response
object, which includes the user person name email along with the token.
Of course also expiration date.
So that this method can be called from the controller, go to the Appsettings.json file.
So it is Appsettings.json file in the ASP.Net core project.
After this existing connection strings and allowed versions, try to add a section that is JWT.
The first property that you require is issuer.
While generating the JWT token as per the standards, you have to add some user claims as a part of
the payload.
So the important properties or claims that must be present in the payload is one of them is issuer that
indicates the domain address of the web API that has generated or created the JWT token.
In this case, our domain is localhost 7221.
So this indicates that in this particular domain we have generated the JWT token.
The second property that must be added as a part of the JWT claims is audience.
Here you have to mention the name of the domain.
Which domain audience can have this JWT token.
In this case, we are targeting to supply this token for audience of 4200.
That is the angular application.
So you must include the particular domain address indicating the domain address of the client application.
Of course it is just for formality and you will write only one value not more than one.
And then you can configure the expiration minutes.
You can write it in uppercase or lowercase wherever you want.
Not a problem.
But I am writing in uppercase here.
I am writing the number of minutes.
How much longer that particular token once generated is valid.
So we have written ten here, which means that token which is generated now is valid for up to ten minutes.
So after ten minutes the token expires.
That means if the server is trying to validate the token after ten minutes for some request.
It identifies that the token is expired already, so it will be treated as an invalid token.
See, this doesn’t mean that the token has to be self deleted, but while verification, it will fail
after this particular time is completed.
So this is an important value which is essential while validating the token.
This expiration time will be included as a part of the token.
These are the configuration values that are required.
And now let us create an actual service that implements the JWT service interface.
Right click on the core project.
Add a new folder.
Services.
Okay, we have not created any service for Crud operations.
Actually, we did the same already while we were learning MVC controllers.
Right?
So you already know how do you create services for crude operations.
I am not doing it right now here, but let us focus on the JWT functionality so we are creating the
same as a service.
Right click on this services folder.
Add new item class.
File name is JWT service dot file and in this a public class implement that interface I jwt service
import from essential namespace.
Right click on that interface name and quick actions implement interface so it generates the method
signature.
Automatically remove this throw statement manually and add the code.
Here we have to read that configuration values from that app settings.
So inject that I configuration.
So in the constructor, we are receiving an instance of I configuration and initialize the same into
underscore configuration.
So we can read that configuration values.
First let us try to read the expiration minutes.
It was written in uppercase.
So we are writing the same here.
Under JWT key.
We have expiration underscore minutes.
So this is the value.
By default the value is in string type.
Let’s try to convert the same into double type.
So we have the number for us and generate the date time value based on this.
So take the current date and time that is UTC Coordinated Universal Time.
Add the minutes value.
So you will get the date and time accurately after the specified minutes.
For example, right now the time is 5 p.m. and the number of minutes is ten, so this method returns
the date and time value at 510.
So we have the date and time for us.
Let’s call it as expiration value.
This is the expiration date and time.
Now let’s start preparing the claims that are needed to be added in the payload.
A claim represents a particular value, much like fields or details of the particular user.
We are creating an array of claims.
First we will include a new claim.
That is the subject.
As I told already, there are certain types of claims that must be included in the payload of the JWT
token.
One of them is subject, so let’s call it as sub.
The sub value or subject value indicates the user identity.
In this case it is user.id for example, because it is the unique value of the particular user, you
can add any value that is unique for the particular user.
Okay, it is JWT registered claim names and import it from system dot identity model dot tokens at the
top.
So here the name of the claim is subject, which is called as sub in lowercase internally, and this
is the value of the same.
Okay.
Similarly, let me add remaining values.
The next value here is that JT.
That is an unique ID for the token.
This ID should not exist already.
So let us try to generate a new GID by calling this new gid method.
The value must be string type, so we are converting the same into string type here.
So here jt indicates jwt id.
That means a unique ID for the particular token.
Every time when you are creating a new token, a unique ID should be generated automatically.
So we are calling new GID every time.
And the next value that must be added is IAT that is issued at.
That indicates the date and time when the token is being generated.
That is right now.
That means when this particular piece of the code is being executed.
So to get the current system date and time, we can say datetime.now.
And you must supply the value in string type.
So we are converting it to string.
And in order to override the local time we are calling Utcnow.
And then you can add name identifier.
That is coming from system dot security clients.
Because this name identifier is not present in the JWT registered claim names, but optionally we are
adding here.
The name identifier indicates the unique value of the particular user.
Already we have added the user id, so let me add email address this time.
Optionally we can add the person name of the user.
So the values of email address and person name are optional.
But the mandatory things here are subject JTI and IAT.
It is as simple as IIT indicates the issued date and time when the token is generated, and a unique
ID of the token is represented as JT I and the subject indicates user identity.
That is, user ID.
That means the id column of the table.
So these are the claims that I would like to include in the payload.
Now we have the payload with us.
After that you have to generate a secret key based on which the signature can be generated.
The hashing function requires a secret key.
A secret key is represented as symmetric security key class.
This class come from Microsoft Identity tokens namespace.
So import the same.
And in this object you have to supply the key.
And we have not added any key in the JWT configuration.
Actually just for demonstration, we are adding the key as a part of the simple appsettings.json file
here.
But in the production level you will store the security key as a part of the environment variables.
Okay, let me add the key.
The development time key may be known to the other developers, but the production level key will not
be even known to the developers.
It will be known by only one person who is actually hosting the application on the production server.
Means generally to the DevOps person.
Okay, for example, I am just writing some random string value.
So assume that this is our secret key which is not known by any person.
It is known to the author only, not by somebody else.
Assume that at least.
So we have to grab this key value from the configuration here.
Hey configuration from JWT section.
Read the value of key and this key value must be converted into bytes.
A byte array.
So system dot text dot encoding dot UTF eight dot get bytes.
So we are converting the string into byte array.
And that value is being supplied as a part of the constructor of this particular class.
So here the key is ready for us.
So based on that particular key only the hashing algorithm generates the hash.
And it is called symmetric key means a single key but not a private or public key.
And for JWT we don’t use asymmetric algorithm.
We only use symmetric algorithm to generate the hash because this is not encryption, But this is hashing
process only and you have to define the algorithm.
In this case we are using 256.
That is the hashing algorithm to generate the hash based on the secret value.
Here H stands for HMS Sha 256 algorithm and S stands for secured hashing algorithm.
So in order to define the algorithm that we are using, create an object of signing credentials.
That come from Microsoft Identity tokens namespace.
And for this constructor, you require to pass the security key that we have created already above,
and also name of the algorithm that we are using.
So security algorithms dot h s AC.
Sha256 algorithm.
Now we are going to create a token generator.
The token generator is responsible to create actual token based on all these information that we have
provided above.
So such a class which is used to actually generate the token is JWT security token.
And for this constructor you require to pass essential values.
The first value is the issuer value.
As I told already, the issuer represents the domain address of the particular web API controller which
has actually generated the token.
And the target audience, that is, the domain by which the token can be consumed or stored.
So we are reading the configuration values over here.
So these values are being read there and being supplied over here as issuer and audience.
The issuer.
Audience.
These two are the first two arguments that you have to pass.
And the next argument is the claims, the array of claims that we have already created above.
I mean all these, which includes the subject JTI, i8 and additional values of the user optionally.
And then the next argument that you have to pass is expiration date.
And also then sign in credentials.
Okay.
You can supply the name of the argument that is expires is the name of the parameter here.
And signing credentials.
So these are the default ordered parameters.
These are the named parameters.
So the issuer audience are read from.
The configuration claims are created above as an array of claims, which contains the user details and
expiration date and expiration date represents the date and time when the token expires.
For example, as per our code, the token expires after ten minutes after the token is generated, and
then the signing credentials represents the algorithm that is HMS Sha 256 algorithm, and that generates
the hash based on the payload and header along with the secret value.
So so far we have just written the code, but no token is actually generated.
The actual said algorithm is not still even started, just we have collected all essential details or
data that is required for generating the token.
But the But the problem is still, this token generator cannot generate the token on its own.
There is one more class that is JWT security token handler.
That is coming from system dot identity dot tokens JWT namespace.
So create an object for that.
And in this particular class we have a method called write token.
So this is the actual method that actually generates the token based on the algorithm that is mentioned
here only.
The thing is you have to supply the complete token generator object as argument.
And that’s it.
It automatically picks up the header values payload signing credentials automatically from the above
mentioned object, and accordingly it performs this particular algorithm process and generates the final
token for us.
So whatever the value that is mentioned here, that is the token.
That token is returned as string value here.
And that is being received as a string value here.
Now you can create and return an object of authentication response.
This is our user defined class which includes with the token value that is generated for us for a moment
and also use our email address.
Of course that email is already added as a token payload.
But the problem is that email address, value or any other claims value which are part of the token
cannot be easily read by the client application, right?
So in order to make the data available to the client, what are the values that are required by angular
directly, such as person name or email.
So we So we are including the email and person name values directly over here.
So this can be displayed directly in the app component HTML for example.
Okay.
The expiration time is the expiration value that we have added here.
So this will be returned by this particular method create JWT token.
So that is why the return type is authentication response.
So overall we have generated the expiration date based on the expiration minutes, created claims for
the payload and created a security key.
And we made ready the hashing algorithm that is HMS Sha 256.
It is not only the one, but it is the most popular one and almost default to use for any developer.
So we can use the same as 99% of the developers do, and we supply the issuer and audience as configured
in the configuration file.
And creating a security token handler.
So this token handler is actually responsible to generate the particular token.
When you call the right token method.
And it simply performs the particular algorithm process, that token value is represented as a string
value here.
So this string value represents a token something like this.
This is a sample token.
It contains the header payload and signature separated with dots.
That is the meaning of this string value.
And that string value is being added as a part of the response from this return value.
In the next step, we have to call this particular service in the controller okay.
We will do that in the next part.
Play Play Play Play Play Play Stop Play Play Play Play Start Start Start