Asp.net core Json Web Token (JWT)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody welcome to digital tech drink in this video i am going to show you and demonstrate you how to create jwt token that is json token in asp.net core application so open up visual studio 2019 click on the project uh select asp.net core web application click next name the project and then click on create and select api because we are going to create a api web api uh that will actually integrate where we will integrate this json token to authenticate the api request make sure that you untick configure for https and click on the create button now once the project is loaded which is already loaded over here make sure that you go to new get packages and install the following libraries i've already done so that we save the time so make sure that you have entity framework for sql server why because i'm using sql server as a backend database then tools design entity framework core and since we are going to demo out json token creating of jwt and asp.net core we need asp.net core authenticated error this is very important now once all this package is installed uh i am going to show you the database which i have already created now i have not get into more detail about the connecting connection connection strings and creating a database and everything which is already done and i have a reference certain modules videos in my description where you can refer on how to create apis and everything uh so i've created this database called jw token dwt demo database which has a table called users and which has following fields username mobile and password now i'll go ahead and just add one username is already there alex with some mobile number and password alex uh i will explain to you what what we will do in this demo so first thing is that uh before i go ahead and show the uh project and demonstrate the working of json token let me run through this repeated just two slides just to explain you the core concept now jwt is nothing but json web token now assuming that there is a client typically client uh initiates an api request to the server and uh where the client will assuming pass the username password to get authenticated the server will authenticate the username and password and then the server will assign you a unique token that is a jwt token json token okay along with the response now typically what happens is the client saves this token in the browser or in in mobile or so that this token which is generated by the server will authenticate the user can be passed for other subsequent request of apis so that the server knows the request from this this uh the client is a authenticated one and it is not uh somebody who's acting and is trying to you know uh do a dos attack or something like that now once in this flow once the user client passes and password the server will assign the validate and assign the token now for the subsequently api request the client will pass the token along with the other parameters of the api now this token will be typically passed in the adders okay and then the server will validate the token password and then validate the token and then give the response back to the client so this is what we are going to do we are going to create an api which will authenticate the user in the database and then generate a token a basis that token the user will then go ahead and say he give me the list of users which is there in your database now basis the token passed in the the server will then assign or share in all the users now typically what does a json look like so basically i pasted the format or typical json token now this json token has three parts one is adder where we have the type of token obviously in this case this is the jwt then the algo what algorithm is used then the second is a claim claim is nothing but uh the user data user rule expiry date when do you want the token to get expired and the third finally the signature so i hope this is the concept is very clear to you guys now let's go and let's practically implement it so now i've already set up the project uh first thing is that i have created entity uh so before that i have created a data contest class i have gone to the app settings and i've added the required database connection string which is over here then i have gone to the data contest class then i've got an entity separated one entity which is matching with a data table that is users username mobile and password another entity i've created called as a user token dto now this entity is for returning the user name and the token so when somebody logs in when we create an api and we pass in the username and password then it this will return this user token dto will be used to written the username and the token along with the request if if the api has successfully authenticated the username and password so this was the entity then we have a data contest class where i'm here and i've used these methods i've created a data set and a user control so this is a controller class where i am going to create the login method now before we jump into this let us write the code that generates the json token jwt token okay now for that as per the standard format which i follow i am going to create an interface as i token i say add new item and i'm going to say interface and i'm going to name it as i token service [Music] okay so change the name now this token will actually this interface will actually implement a public interface called sorry this is already so we need to make this voltage sorry and this is going to implement a method called create token jwt token and user user class as a parameter i will pull in the reference of entity so this interface uses a method implements a method called create jwt token and takes users entity as a input parameters now we go ahead and create the actual method services and we create a class that is going to this is services now typically this service will inherited i token service so this uses this library and then and is going to use this method so now you don't require to call this already correct so this service is actually going to use create which actually is going to implement the actual method for creating the jwt token now let's go ahead and first define some so we are going to create one read only select security key define a variable uh symmetrical security key is a key that actually does both encryption as well as liquidation now we need to add certain library aware i guess it's not implemented using microsoft identity model token so this is what a reference we need to do symmetric symmetric security key is a key with single key that encrypts as well as this decrypts the key that we are going to pass there is something called asymmetrical security which uses the public in the private key concept we are not getting going to you know cover that right now in this video because for uh the demo purpose we uh we need a symmetrical key and i can demonstrate the token validation and validation of the services once we have the key we create a constructor class okay we don't want to pass this key what we are going to use is a configuration we are going to use the i configuration because and we are going to reference the token key so we are going to say key equals to new symmetrical key symmetrical security key and encoding eight i think so we need to pull in the system.text plus eta dot get bytes we're going to use config and token key now we have still not implemented this we're going to show you so basically what are we doing is that we are actually creating a symmetrical security key a key which will encrypt and decrypt the tokens and we are going to use token key configuration we shall define which will be a key for us so whenever there is a json token it requires key then it requires a claim and then the signature which i explained to you in the start of the in the ppt now we go to the json setting and we add that key over here already so you can name this anything like anything which you can use token broken key and i can see this is my master key yes talking okay so i have defined the key so this is going to answer this can be anything this this value can be anything where it can be any value which you can put so now this will take up that value obviously symmetrical key requires a get byte so it convert that into byte and then the key will be given generated now let us do the actual implementation of creating the token so so what are we going to do in this method is that we are going to structure or construct the token first thing is define a variable called claims so we are in json token there's something called claims we are claiming that claiming users so j wt registered claims names so we're going to pull in certain class first is system.security.claims and then we're going to pull in using system identity model token jwd okay a new claim what are we claiming the name id and what user we are using we are using user dot username from our entity class so this becomes our first claim this is the structural json which i am showing then we have where credentials where we are going to pass the key new signing credentials we are going to pass in the key which we generated in the constructor and we are going to pass the algorithm and we are going to take the the most secure algorithm for hma c sharp 256 signature this this we have here so this is becomes our signature so this becomes a credential now the third part of json token is a token new security token descriptor here we are going to describe the token that is name identity claims this becomes for whom we are creating the json token and then you say expire so your token depending upon your security uh you know uh stringent house to reduce your security environment what is your base requirement for the security so in this case i'm saying add minutes and then sign a credentials equals to craigs so as i explained in the start json token as the type of token and the algorithm the claims and a descriptor so here we have constructed the claim whom you are claiming this token to be issued for then the credentials for that token and the token descriptor which has the which has when the token is going to expire with whom the claim the claim is and you know all that which i may explain with the first part of the session now after this we security dot create and then we pass the token discussion and then we return the token to the calling method right so we have created a routine to generate the token jwt token okay so as i mentioned claim credentials that is the key and the entire descriptions are token and then we write code to create the token and return the token back to the calling method so now we have the methods ready so we can implement the actual class now we go back to our users controller and then we go back to user controller make sure that you add the data context class which are created inject that in the constructor and now we write in the method for login let us open so database is already open let's add some more user to it okay now we come over here first method is we are going to write is http put post login and you simply task action is a user token so we are going to in the user token detail user login we are going to pass in the entity user game this is so we are going to write the condition then we are going to return unauthorized access let's say invalid username else if everything is good we are going to return the user dto and then we are going to implement the here we have forgotten to call the i token interface so we just do that i token service let's say token we call in the required language and we need to also pass it the same token all right so now we come over here in the method and we see create data and we pass it the user semicolon so now we have done a very simple implementation uh we are going to use a login method now and in the same login method we are going to generate we are going to authenticate the user as well as they thought user is not indicated we are going to generate a token so uh why don't we set a debugger over here and let's open our postman let's run this you can refer to my previous video i'm sure i've put that links in the description where i showed you how to use postpan how to use create apis and everything here i just focused on creating the routine for uh generating the token so uh we will now project is running so we will go to login and here is the url okay uh user and login see i have created a http post your login name and then i have passing the username alex master alex and i'm going to click on save so what has happened let me just check okay down okay okay so i have done a big blender i have not injected this in the app startup class so that is an issue because once you create the services you are supposed to inject the same in your app startup class otherwise it will never know that what method needs because that was the issue basically so in order to do that okay you need to go to the startup class here in the services aca services dot ads cooked and then you call the i token service and the token class i'll pull in the required interface references so what is this at scope basically we have used we are using this so that it the lifeline of this service is within the http service and the scope is within the http service and obviously you can do this implementation without creating a interface and adding that over in the startup class but it is a better practice so that you can use the same method to do mock testing unit testing and it's a it's a it's a better standard it's a better practice to do this it's a good practice to do this you know so i forgot to implement that i forgot to add this uh reference over here and that is why we were getting this error object not uh you know available or not formed so i guess now it will work i'm sure okay so let's do this yes since now it has come over here now if you see it is it has passed alex alex with the password and we are going to uh add a breakpoint and it is yes so it's come over here in this method now see what is i will step down one by one so first is the claim username alex and then it is uh it is it has already picked up the key uh which is in a byte format uh and then it is uh setting up the description of the token then it is created in token and it is returning the token back so now if you look at the postman you see it is authenticated the user and it is shared the token now this token becomes a base which we will use in calling the other i'll also demonstrate what happens if you don't pass the token for that let's do one thing let's since our main code is implemented let's quickly create two methods one we should return all the data and one which will uh return data but it will we will force it to authenticate authenticate the method using this token so if there is no token provided you will not get the data from the method let's do that i'll show it to you right away so we are going to create two methods simple so let's do that let's say http get and so we are going to use allow and request what does this mean that you are saying the method that anybody can request it without passing any token and then we say public sync ask users and we are going to say okay get all users return await yes fine so this is not going to force to pass the token which we needed but we might we will create one more get method where we are going to so you want to run and check this so we will do that so let's go ahead and try to get the records so get all these this is a uh api that will get all the users yes it is running so we click on api you can see alex james and billy all three users are very distracted so guys we checked how we were able to fetch this record uh from the from the database by using this method and using allah anonymous where we didn't have to pass any token key or authorize or authenticate the api request now uh how do we force the api is the method and solution for an token to be passed and a valid token to invest now before we get into that so first thing is that we are going to create a method and it will be the same we can use the same method but instead of allah analysis we are going to say authorize and then we are going to say get users so restaurant is the same now for in order that this method should work and it should expect and token we need to add certain code in our startup dot cs file so first thing is that we are going to tell the service to use the token mechanism which we have set up and the key which which is there in our app setting json file so for that we need to write certain few lines of code so we say services dot add authentication and we are going to call jwt mirror defaults and we are going to say authenticate scheme options options enter and options.token token validation parameters new token validation parameters and we say valid validate issue signing issuer signing e through so why did the issue signing key equals symmetrical security key and we use the same code encoding dot udf dot get bytes and we say configuration token key then validate issuer cause and and validate audience semicolons here and then here for us these two code are important where we are seeing to violated the api http request and user the key that we have configured so these two methods actually forced foreign foreign https request to expect a token a valid token now after we add this code in the services class okay config config services class we need to go to config and after app dot use routing and before use authorization we are going to say author use authentication that's it now once we set up the startup.cs class we come back to our users controller and we run this code now the one which we wrote only difference is authorized remember to add the authorization now once you authorize this method the code setup in the config class will trigger as well as it will force you to provide the authentication provider token key now let's run this first and see the error which we get when we don't pass the token so i say a new request and i say get and i say this is get users okay and i'm just simply getting a set and let's expect what support sorry i didn't run this one section okay okay so i click on send and see what happens what is error 404 not formed api and this is okay so i forgot this so this is it uses okay now let us see the error which will be displayed 401 unauthorized so this is an unauthorization right it's expecting a token a valid look now let's go ahead click on login and let's sit login alex and get a valid token so this is the token which we got from alex after he was successfully authenticated where our method was called now we come back to our new request here okay we are getting an unauthorized access what you need to do in order to pass that the token in the header click on the address click on key select authorization in the value type error space and paste the key token key now let's see what happens yes we got it now if i change the value of the token look at the error which again i remove i had one in between e and c unauthorized so this is the way like you know here we are able to guess so so i hope uh you guys were able to understand uh i will just reiterate the structure again we created a project we created an interface uh which which and and implemented a service which actually created a token uh by passing in certain values and we use the postman we created sorry we created methods where we demonstrated a method which allows uh to fetch the data without passing any token uh and then a similar method which actually authorizes and force forces the method to know passing the required we showed you how do you set up the startup.class to accept the service to uh pass in the token and use not only authorization but also authentication so i i guess guys you liked the video it was insightful i request everybody to please to subscribe and like the channel also also very important thing please do share your feedback and also to share what are the videos you like me to create in in asp.net and you know i am also going to share videos on asp.net aws i recently got certified uh as a solution architect so i expect that you share me the feedback i expect that you people will like and subscribe to my channel thanks a lot guys
Info
Channel: Digital TECHJOINT
Views: 144
Rating: undefined out of 5
Keywords: asp.net core, json, json web token, asp.net core jwt, implementing jwt, web api jwt, authorize web api, authenticate web api, create JSON
Id: g9iWy_YuC34
Channel Id: undefined
Length: 41min 17sec (2477 seconds)
Published: Mon Oct 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.