JSON Web Tokens (JWT) in .NET 6 Web API 🔒 - User Registration / Login / Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone this is Manoj and welcome back to my YouTube channel in today's video I am going to discuss about one of the most important topic of asb.net core web API which is JWT what is JWT Json web tokens commonly known as JWT is an open standard to pass data between client and server and that enables you to transmit data back and forth between the server and the consumer in a secure manner as you can see on our screen we have a client we have a server so from this client and we need to pass some information like username and password or you can say email and password and that goes to our server and then server validates username password if that is a valid user then it creates a secret key which is a JWT and returns back that took it to the client and then client stored that digital JWT token and again then client try to access our API resources whether it is a guest HTTP get or post put delete then with that request client needs to pass the same JWT token to access the API resources all right basically is a combination of three sections one is header header provides metadata about the type of data and the algorithm to be used to encrypt the data that is to be transferred second we have payload the payload represents the actual information in Json format that is to be transmitted over the wire third and last is signature the signature others to the Json web signature specification and it is used to verify the Integrity of data transferred over the wire all right so till now enough theoretical knowledge let's start the Practical approach by creating a new project so for this video I'm using visual studio 2022 you can use any version of Visual Studio which will support.net core so from here we will select.net core web API and click on next let me give name JWT token example and let me change the location click on next so it will create a.net core let me uncheck this https create so this will create our DOT net 6.0 project so our project has been created as you can see this is the default page let's close it and open the solution Explorer all right so this is the default file and folder structure now the first step is we have to install one package so right click on it manage new get packages and go to the browse and here we have to type Microsoft asp.net core authentication.jwtbr all right so select it make sure you will choose the right version so I'm going to choose 6.0.0 and install if you will select the higher version then it will say that is the compatibility issue all right so make sure you will select the 6.0.0 version all right so the package has been installed let's close it now the second step is we have to register our JWT authentication so open this program.cs before that we have to import our namespaces so using Microsoft dot asp.net core dot authentication dot JWT Bearer and second one is using Microsoft Dot identitymodel dot tokens so we have imported our namespaces now in this Builder so Builder Dot services dot add Authentication and here we have to pass JWT be error defaults dot authentication scheme and Dot add Bearer token options so here we have to pass some parameters to create the JWT token so the object as options Dot token validation parameters is equal to new now the first one is validate issuer is equal to true validate audience true and validate lifetime and now valid user sorry where it is sure and that we will take from our app settings so I'll come create that JWT configuration in app settings.json so Builder dot configuration and now we have to pass the app settings key which will be JWT colon issuer now valid audience again that we will take from our app settings don't worry I'll keep the enough information and app settings also so that will be coming from audience and the last one is issuer signing key new symmetric security key and again we will use our encoding so encoding small and for that we have to use this namespace system.txt so encoding dot utf-8 dot getbytes and this will come from our app settings also so let's copy this and change the key as key we will give the key with the property name key all right so our authentication parameters is complete now below here we have to use app Dot news Authentication save so we are done with our program.cs now let me tell you what we have these parameters so what is this this valid issuer that validates the server that generates the token now the second one valid audience it basically validate the recipient of the token is authorized to receive now this validate lifetime this check if the token is not expired at and the signing key of the issue is valid or not all right now valid issuer and we also have a signing key so basically signing key validates the signature of the token and additionally we have given this issuer audience let me give these information in app settings.json so go to selection Explorer and open the app settings.json and here let's add another key so JWT and inside this first let's copy this issuer and also we have to pass this audience and finally we have to give another property key so let me give let's say I'm giving my website name connected programmer .com I'm giving the same value for audience and the key let's say a b c d any key the strict key all right you can also use some online unique key generators so we are done with our app settings dot Json also now we have to create a user model to pass username and password so create new folder models and inside this model let's add a new class called users and inside this user I'm going to pass two properties so shortcut is prop tab it will generate your property so the first one is username again prop tab data type and the name of property password password so our model is complete now let's create a controller which will authenticate this user and then generate the token all right now in the controllers right click on it add controller click on API API empty let's give a name login controller and first of all let's create the Constructor so shortcut is c t o r then hit tab it will create your Constructor and now we have to pass eye configuration so private I configuration config and here also I configuration configuration and here underscore config is equal to configuration so our Constructor is ready now let's create a method which will authenticate the user all right so private users control dot we need to use this namespace because this class is inside this models now we can access this user authentic ate user and this will accept this user's class user if user Dot username is equal equal admin and and user Dot password equal equal one two three four five then return users underscore user is equal to null and then underscore user is equal to new user and here we will pass username is equal to one of those and password okay we will only use this one and finally return underscore user I have created a method with authenticate user and this will accept the properties from our front end whether you will hit this method from your react.js angularjs or from your Postman so it will accept the parameters and it will check if this username is admin and password is one two three four five then it will return the actual user with the name manuscript otherwise it will return user as null all right here I am using the dummy values but later on I will connect this information with the database and a table and we will see the real users all right but for the timing I'm using the static values now let's create a generate token method which will generate the token so private string generate token and this will take again users parameter so first where security key new symmetric security key same let's go to program.js and copy this instead of this Builder Dot configuration we have to use underscore config and where credentials new signing credentials security key security algorithms dot now we have to pass you can also pass this 256 or 512 I'm going to use this 256 algorithm so now let's create the token and the token will take our issuer and our audience all right we can also pass the expire and credentials so let's create a token so where token is equal to new JWT security token here we have to pass some values so the first value we will take this JWT issuer copy and instead of this Builder configuration we have to pass our underscore config object and if I press comma we have to pass the audience let me again copy this and pass the same and change the key as audience and let's pass null and after that we have to pass the time so expires date time Dot now dot add minutes I'm going to give one minute time for the expiration and after that we have to pass the signing credentials credentials so our token is complete now let's return this so return new JWT security token Handler Dot write token and pass this token object so basically it will create and return the token through this method now we have created our authenticated user also generate token now let's create a login method which will accept the parameters of this user and that will generate the token so for that let's use allow an ominous tag so it will bypass the Authentication and that will be a HTTP post method so public action result login and this will take users as parameter I action result is equal to unauthorized and where user is equal to authenticate user and pass the user which we are getting from the parameter so if user underscore is not equal null then where token is equal to generate token based on our user and response is equal to okay new and we will pass token as token finally return response save so in our login controller we have created a login method which will accept the users as parameter and then it will pass this user to our authenticate user if that is valid then it will again go and generate the token all right so we have done all the things now let's try to build the solution and run the project and try to create the token so we'll succeeded let's hit this schwarzweiger is loading perfect Swagger has been loaded now let's click on this login try it out and let's go to the project and pass these values so admin and one two three four five execute let's see if we get the token perfect we have got the token all right so let's create another controller and then we'll try to use our JWT token add click on the controllers add controller API API empty let me giving it name employee controller so inside this let's create first http get public string get data and this will return simple string authenticated with JWT and let's decorate this with authorize tag and let me also give a route get data let's copy this and paste let me change this details so this is without authorize and let's also create one more HTTP post again public string add user and this will take users class as parameter so user and return user added with username plus user dot username save Ctrl shift B so let's build this project build succeeded try to run foreign has been loaded perfect so first let's try to generate the token so try it out and we have to pass these values as admin admin and one two three four five execute so token has been generated let's copy this value and now to test these apis we have to use our Postman so open the postman so first of all let's try to get this so try it out execute this will give you some information so this is our URL so let's copy paste it over here and in the headers we have to pass this token let's copy this token again and in the key we have to pass authorization and in the value use Bearer and the token value see I am using one outdated Postman so we I don't have any Bearer automatically uh in this authorization all right but if you're using the latest Postman so you don't need to pass this Bearer you will find this in authorization all right so now try to send this so you can see authenticated with JWT now if I remove this let's say if I uncheck this now this is not considering this BR token if I try to send this again so you see I'm getting 401 unauthorized all right so let me include this so authenticated with JWT and if I try to execute the another one which is details try it out for that we don't have a need any authentication so we will get the same respond all right without any JWT token now let's try to execute this post so try it out execute so let's copy this URL go to postman create a post request so URL in the headers authorization Bearer space and your Authentication let's copy paste send in the body we have to pass this body so again from the Swagger copy this body paste and let me change the value Manoj deshval okay pass one two three four five click on send you see user added with username Manus deshwal all right so this is how we can generate our JWT token and also we can enable our apis to allow this authentication to authenticate our request whether it is get post put delete all right so any API which you want to you know obey the authentication rule you just need to decorate that with authorize and it will automatically use your JW to taken token authentication all right so I hope this video will useful for you and you have a clear idea how to create a JWT token and how to use it all right and one thing I want you to do some r d for this login controller here I'm using the static values I want you to create a database connection and from there you have to pass these value from the front end and instead of matching these static values I want you to match these values from the database values using stored procedure or using Entity framework that is totally up to you which approach you want to use you can use but instead of this static approach try to use the database driven approach all right and also for this employee for this ad user try to insert these details into database again with this database driven approach all right so this is about today's video and again I'm going to do one announcement on 15th February I am going to launch my react.js course and for the first 100 users the cost of this course will be triple 9 only the actual cost of my course is 3500 but for the 100 users the cost will be triple line only I am leaving a course Link in the description you can follow that link and pre-enroll yourself all right so I'll see in the next one thanks for watching take care bye
Info
Channel: Manoj Kumar
Views: 25,060
Rating: undefined out of 5
Keywords: token authentication, token authentication explained, token authentication c#, token authentication vs jwt, token authentication postman, jwt, jwt token, jwt authentication, opaque token, jwt.io, asp.net core authentication, asp.net core 7 authentication, asp.net core jwt, asp.net core token authentication, json web token, json web token authentication, jwt token authentication, JWT Authentication, using jwt in .net6, Build api with jwt token, JSON Web Token, manojdeshwal
Id: KHXYdIueipc
Channel Id: undefined
Length: 26min 29sec (1589 seconds)
Published: Mon Feb 06 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.