JWT JSON WEB TOKEN in Asp .NET Core WEB API in MVC .NET 7

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello all this is Anis with you welcome to my channel in this video we are going to see what is JWT and we are going to create a JWT secured API server project and API webclient project to access the secured API by passing the JWT tokens what is a JWT JWT stands for Json web tokens jabilities are most commonly used to identify an authenticated user they are issued by an authentication server and are consumed by the client server to secure its apis Json web token is an open industry standard used to share information between two entities usually a client it can be a mobile app or desktop app or a MVC web app or whatever and a server usually an APS server or a web application JWT contain Json objects which have the information that's needs to be shared each JWT is also signed using cryptography hashing technology to ensure that the Json contents also known as JWT clients cannot be altered by the client or malicious party is called self-continent tokens the JWT can contain the user's details not just the session ID like a cookie but other custom data such as username departments even permissions together with the tokens expiry time so you don't need to query a database for that information this is completely unlike an opaque token which by its very nature it's just a meaningless jumble of alphanumeric characters how jwd tokens saves database space and improved database performance JWT tokens are stored only on the client the server generates the token and send them to the client but the server did not save the tokens anywhere the client then submits the JWT with every request this saves database space and performance because the server does not need to query the database to validate the token if this seems to be very confusing no worries we will understand better while doing the application so let's start developing the application start Visual Studio 2022 and click the button label desk create a new project then select asp.net core web API and click the next button in here give the project name as JWT test after that set the location as C column slash jwd test and leave the checkbox labeled as Place solution and project in the same directory and then click the next button and in here select the framework as dotnet 7.0 standard term support then leave the authentication type to none and then leave the checkbox label desk configured for https as checked after that leave the checkbox labeled as use controllers as checked then leave the checkbox labeled as enable open API Support also as checked then click the create button and wait for the scaffolding task to complete after that click the view menu and click the solution Explorer then click the nuget package manager and select the menu labeled as manage locate packages per solution and here click the browse tab in the search box type microsoft.asp.net core dot authentication.jwt Bearer then press the enter key and select the first item from the search results from the right hand side check the JWT test project from the projects listing grid and click the install button to start the installation in case if you are prompted with the preview changes dialog box press ok then press I accept in the license acceptance dialog box and wait for the installation to complete after that search for Microsoft dot identitymodel.tokens in the Nugget package manager for Solutions then select the latest version and click install in the same way after that browse for system.identitymodel.tokens.jwt and install it also in the same way now we have installed all the required packages then open the app settings.json and create a section named JWT after the allowed house after that create three key value paths named key issuer and audience inside the JWT section and then set some secret complicated text value for the key this is very important and this is like password for your jwd token never share this key to anyone next set some value to the issuer basically it can be the company name or the company URL or your name I use my name here then the next item is audience the audience value is very important many programmers get confused on this topic they don't understand the real purpose of this audience tells for which app the API server is created for by end of this tutorial we will create two API servers one with audience as customers and the other is for suppliers so that the customers cannot access the suppliers API and the suppliers cannot access the customers API it is going to be very interesting so please stay tuned okay now we are done with the app settings.json file and next open the program.cs file in here first declare a variable named TK conf and load the JWT section of the app settings.json into it after that create the token validation parameters this is very important this tells the server on how to validate the received token from the client if you get errors like me then add microsoft.asp.netcode.authentication.jwt Bearer namespace followed by the Microsoft Dot identitymodel.tokensnamespace and system.txt namespace to the using section wow now the errors are disappeared let's see the parameters one by one set the validate issuer equals to true this makes the server to check the issuer of the token if you really don't want to check the issuer then you can make this as to false then set the validate audience to true so that it checks the audience claim of the received token then next is validate lifetime parameter set this key always to true so that the server rejects the expired tokens after that set the validate issuer signing key parameter to true this is also very important so please keep this always to true after that load and set the valid issuer and valid audience parameters from the take account variable and then load the JWT pass press key from the TK count and then create the symmetric security key and set it to the issuer signing key parameter this key will not be sent with the JWT key so that no one can tamper the jability key but they can decrypt and see the contents of the JWT key that also I will show how to do later in this video then the next line is very important line add the JWT Bearer authentication to the Builder dot Services as shown after that in the program.cs file we need to add app.use authentication and app.use authorization middle verse just above the app.map controller's middleware okay now we are done with the program.cs file and next let's create a model to pass the username and password actually we can pass this without model also I mean simply as parameters but it is better practice to pass it through models so let's create a model and name it as login model this login model will have only two properties named as username and password both the properties are of type string then delete the weather forecast model and the weather forecast controller which came up with the scaffolding task we don't need this anymore and next let's create a controller and name it as login controller make sure you select and create the API controller and not the MVC controller notice the route attribute of the controller it should be API controller and it should also have the API controller attribute In The Head of the Class name and now add the authorize attribute to the class here we are setting the authorization level in the class so that all the methods of the class will need a authorization token or identity then declare a private read-only variable of type I configuration and then add the Constructor method with the iconfiguration parameter and set this parameter value to the read-only variable underscore config and next add a method with the HTTP post web and name it as login actually the name can be anything here only the Web Matters then add a parameter named as login of type login model this parameter we will receive from the body section of the HTTP request that's why we put from body before the parameter next we want to make this method available for everyone so add the attribute allow Anonymous to the head of the method after that we need to create a method named as generate token to this method we pass the username and create the jwtip token to generate the token first we need to get the key from the config.get section of JWT key after that we should encrypt the key using the Sha 256 algorithm then create the climbs array here we are not using the climbs so we can set the climbs parameter as null also I will create a separate tutorial for climbs and roles very soon for now just pass the username as the climb to the claims array okay now we are ready to create our token so declare a variable named as token and set it to the new of JWT security token by passing the required parameters notice here I have set the validity for the token as 15 minutes you can set the validity as per your requirement then return the created token to the caller method using the write token method of the JWT security token Handler class after that go to the login method and write the login credentials checking code if the login name and password is valid then create the token and return the token inside the OK response in case login failed then returned the bad request Response Code with the message as login failed then next let's create a method named as test this method is a secured method so that it cannot be accessed without passing the token if a valid token is passed then this method will return the OK result with the message saying token validated successfully otherwise it will throw an error saying 401 unauthorized okay our project is done let's run and check the application here first I am trying to call the test method without logging in click that write out button followed by the execute button notice it has thrown the 401 unauthorized error now let me login by calling the post method in the request body Json enter username as anise and password as123456 after that let's press the execute method notice the login is success and we successfully got the JWT token this token is valid for 15 minutes now press the get button and then click the try dot button after that press the execute button still we get the 401 unauthorized error this is because we did not pass the token and there is no option in the Swagger interface to pass the tokens actually there is an issue in the Swagger UI configurations in dotnet 6 and above to fix that we need to do a lengthy workaround and it is out of the scope of this tutorial so to make things simple I have made a API web client project just like Postman please download this project from the shown URL or else use the postman instead after downloading the web client project extract and run it now press the create button and then copy and paste the API URL to the API address text box after that click the create button as expected we got the error saying response code is unauthorized this is because we did not pass the token the same issue happened in Swagger ey also okay press the back button of the browser and then go to the Swagger UI and login using the username and password then copy the token string to the clipboard then come back to the code AS web client interface and then paste the token to the JWT token text box then press the create button perfect this time the API call is completed with the success code so our JWT authorization works fine but this is the basic way still the tutorial is not completed I want to teach more about JWT to you so please stay on so far we are only using the JWT Bearer but how to integrate jrot Bearer with the asp.net core identity so that we can create jwd tokens for the authenticated users to do that first let's install the Microsoft dot Entity framework core dot SQL Server so go to tools then click nuget package manager then click manage nuget packages for solution and then here click browse tab after that enter EF core SQL server in the search box then select and install the first result which is Microsoft dot Entity framework core dot SQL Server since we are using dotnet 7 select the latest package for net 7. as of this recording the latest version is 7.0.5 Okay now click the install button if you are prompted with the preview changes dialog box then click ok after that click I accept in the license acceptance dialog box okay now if code for SQL Server is installed successfully next we need to install the microsoft.asp.core.identity dot Entity framework core so in the Nuggets solution manages browse tab enter microsoft.asp.netcode.identity dot Entity framework core in the search box then select the first search result and press the install button and click OK in the preview changes dialog box in case if you are prompted after that click I accept in the license acceptance dialog box okay now the identity framework core is also installed successfully next we need to install the EF core tool so type EF core tools in the search box then select the Microsoft dot Entity framework core dot tools from the search result and click the install button press OK in the preview changes dialog box then click I accept in the license acceptance dialog box perfect now all the required packages are installed so we are ready to program now open the app settings.json file and add the connection string section and add the connection string for your DB please notice the connection string carefully I am connecting to my local SQL server with the trusted connection and with the trusted certificates to the jwd test database use set as per your requirement or use the same as mine after that add the appdb context class to do that right click the project in the solution Explorer then click add and then click new item in here give the file name as appdbcontext.cs and click the add button and next add the Entity framework code namespaces to the using section after that inherit the appdb context from the identity DB context with the type as identity user then add the Constructor method for the app DB context class as shown and then open the program.cs file after that add the app DB context to the services collection using the commandbuilder.services.appdb context in case if we get the compile time errors like mine add the JW test namespace and the Microsoft dot Entity framework core namespace to the a using section of the program.cs file then we need to do the database migration so go to the package manager console window and here type add migration space create DB and press enter after that type update Dash database to update the changes to the database now let's go to the SQL Server management studio and we will make sure that the database is created okay the database is created successfully we can see all the identity related tables in the database next we need to modify our login controller to validate the username and password from the database as of now it is hard coded so to do that we need to create two private read-only variables of type sign in manager and user manager after that we need to add user manager and sign in manager parameters to the Constructor method so that it will be served by the dependency injection then assign the parameter values to the read-only variables respectively then add a method named as authenticate this is the method which will check the username and password using the sign in manager and if the user is validated then it returns a retrieved user from the user manager otherwise it returns null now we need to modify our login method to use the authenticate method for user validation so change the login method as shown here we are checking for the user.result the user dot result will have the authenticated user or null then next we need to add the identity service in the program.cs file so add the identity service below the add DB context method then we need to create a controller named as register controller using this controller we will register the user so create a API controller and name it as register controller then add the read-only variable of type user manager to the register controller next add the Constructor method to the register controller then create a method named as register which accepts two parameters named username and password this is the method used for the new users to register the details please notice the method carefully this method can be accessed by all so add the hello Anonymous attribute to the method head okay now we are done with the project let's build and run the application let's click the post button followed by the try dot button to register our first user then enter username as Anis and password as one two three four five six and then press the execute button perfect the user only sees registered successfully Let's cross check by going to the SQL Server management studio and browse the asp.net users table yes we can see one user created in the asp.net users table now let's request the token from the login controller by passing the username and password let's enter the username as Anis and password as one two three four five six and then trust the execute button perfect we got the token now let's go to our code AS web client to check the login API copy and paste the API URL to the API address and Trust the create button perfect we got the Response Code not found actually we are supposed to get 4.1 unauthorized Response Code but it is okay I will explain why we got not found Response Code now press the back button of the browser then copy and paste the token from the API server now press the create button oh still we are getting the error response what happened our project stopped working but no worries we will fix it actually the problem is in the program.cs file so open the program.cs file to fix the issue here if you see we have two authentication providers one is ASP net core identity provider and the other is JWT Bearer authentication provider since we use two providers the authentication system conflicts and stopped working so to fix this issue we need to tell the controller to use which authentication provider so open the login controller and scroll up to the top of the controller now comment the authorize attribute and then add the authorized attribute with the authentication schemes set to JWT Bearer defaults dot authentication scheme then build and run the application now first try clicking the get method from the Swagger user interface perfect now we are getting the Response Code as 401 unauthorized very good and notice the expected authentication is set to Bearer now copy the URL and paste it to our code AS web clients API address text box then press the create button notice now we are getting the 401 unauthorized error here also then press the back button of the browser and go back to the API server project and here click the post button and then press the try to button then enter username as anise and password as123456 then press the execute button perfect we got the JWT token now copy the token to the clipboard and then go back to our code AS web client project then paste the token and press the create button wow now we got the message saying token validated successfully so the project is working fine now copy this token and go to JWT dot IO website then paste the copied token to the encoded text box as shown see the payload text box shows all the claims of the token we are able to see the expiry date and time then we are able to see the issuer and audience climb so using these details can someone create a similar token and will they be able to access our site no no that's not possible because no one can decrypt the password key of the token in our case the password key is I am Anish from India which is boxed in green without this key no one will be able to make similar tokens and you can trust your site is safe but if you give this key then the key holders can make the duplicate tokens and can get the access to your site so be careful and keep this key safe okay then what's next I need to explain you the purpose of the audience climb so I will copy this project and paste it in a different folder and let's name that folder as jwd test dupe after that let's rename the project name also to JW test dupe and then open the JW test Loop project after that open the launch settings.json file in here change the HTTP port to 7231 and then change the https port to 5317 and then change the application URL Port of the IIs settings to 36241 and 44302 or whatever you like then after open the app settings.json file and here change the audience to supplier app okay we are done now build and run the application so now both the API servers are running side by side and both the projects are sharing the same database and same password case and same issuer but they have different audiences so let's log into the JWT test app and generate the key first then after copy the API URL and the JWT key from the JW test project and paste it to the codus web client project after that click the create button to pass this key to the JW test API server perfect the key is accepted and working fine now press the back button of the browser then change the API address to point the JW test dupe project API listening URL now press the create button to pass the same key to the JW test dupe API server notice we got the error 401 unauthorized because this JWT key is for the generated test server and the JWT test dupe server is expecting a different audience climb I mean supplier app climb which is not there in this token because of that it rejected the key so from this tutorial we have learned lot about the JW tokens and the API servers but still lot of things to come like rolls climbs and creating a API crud application using JWT tokens so please wait for the part 2 of this tutorial which will be uploaded very soon with this I am completing this video before I sign off I request you to subscribe and share this video I would appreciate if you would like and subscribe to this channel so that you will be notified for all of the new videos that I will be posting thank you and bye for now
Info
Channel: CodeS
Views: 5,401
Rating: undefined out of 5
Keywords:
Id: WHa6Qh5zCc4
Channel Id: undefined
Length: 37min 51sec (2271 seconds)
Published: Mon Apr 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.