Authenticating Web API Using ASP .Net Identity and JSON Web Tokens (JWT)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to this video my name is father and today I'm going to show you how to authenticate your web API using.net identity json.token and Entity framework then stay tuned we have an empty API application here first I'm going to create a model for something like employee and I'm just giving some property to it in this video we are not going to use this model I'm just going to create Entity framework migration for this model and the identity model that we have how by adding some dependencies let me select Entity framework I need to install Entity framework core and then I need to install Entity framework Core Design let's select version 6 and install it and after that because we are going to use SQL Server engine I'm going to install Entity framework for SQL server and install it because I'm going to create identity database I need to have asp.net code.identity I need to install ASP core identity and ASP core identity Entity Framework let's go back to the project build everything and create the context I'm going to create a context contexts and I'm going to call it alt demo DB context let's create that one and inherit from instead of inheriting from DB context I'm going to inherit from Identity DB context which is an implementation of DB context which has some other tables in it identity DB context and we need to create a Constructor for that and pass DB context options I'm going to call it option and pass it to the base method as well and now I'm just going to create a property for DB set that I have for employee and call it employee fine everything is ready I'm going to use dotnet CLI to create a migration for doing that I need to go to my CMD and check if I have it installed or not using.net tool list.g because I usually install this kind of tools globally I don't have it then I need to install it I'm going to install dotnet Entity framework as a global tool and this is the command great let's build our application go to the Powershell and this is the address that I have for this project fine and I'm going to create a migration and the command is.net EF migration add initial initial is the name it's a convention by convention we give it to that it is going to create a folder here for me as you know if it works no it is not working why because it is telling me that it cannot create the object why because we don't specify the connection string let's create a connection string I have the connection string here connection string in the app setting we have one connection string and then default connection string it is going to connect to the local DB database out DB and trusted connection should be true and multiple active results that should be true as well in the program I'm going to inject it by Builder and pass the name which is out demo DB context and we have some options for that we are going to tell it that we are going to use SQL Server and give the connection string to that using builder.configuration dot get section and then the name that I have which is connection strings and after that default connection string and I want the value of this section I need a semicolon here and another one here fine let's go back to the developer publisher and create it initial the initial migration should be placed here fine as you can see it is going to create asp.net rules asp.net users and some other tables which are related to our identity framework let's update the database and let's refresh it open it as you can see I have employee here I have migration table here and we have some other tables for asp.net identity fine asp.net identity is responsible for creating users managing users login logout and managing the claims we are going to first create a user and login for doing that I'm going to create a controller and call it out controller let's create it like that and the controller API controller empty and call it out controller I'm going to create a login method first it should be public async task I'm not sure what I'm going to return just let's stick to the task and login and it should be http get where is get here fine and what we are going to pass it we are going to pass it a username and password for logging in then inside the model I'm going to create login model or maybe login user and it will have just a username and a password let's go back to my controller plugin user I'm going to call it user but before logging in a user first we need to create a user then let's create another method I'm just doing Ctrl C and Ctrl V HTTP post yes I am going to register a user I guess I'm going to return a Boolean I'm not sure let's stick to the Boolean for now and we are going to register a user for doing that I'm going to create a service services and out service in outservice I am going to create a method for registering a user using public I think task and I'm going to create it as bull register user this method accepts a login user let's call it user and how to create a user for creating a user we need to use a class called user manager and we need to tell the identity but implementation of user we are going to pass to that then we are going to create a Constructor and passing identity user let's do it see tour tap tap user manager identity user and I'm going to call it user manager let's create a field for that one but how we are going to inject it here let's go back to the program.cs file that Services dot add identity inside the identity we need to pass two types first for our user and then for roles identity user and identity rules we can pass some options to it for example options and in the options we can say things like options that password as an example require the unique Channel a character requires none alphabetic required lens and let's have it length should be at least five and then we are going to tell it that this identity is going to use my Entity framework and my DB context we need to pass the DB context to it add Entity framework store and it is out demo DB context file and then we are going to tell it what kind of token we are going to use and I'm going to ask it to use the default token provider let me press a tab here to make them more readable here in the out Services I have a login user it is time to create an identity user out of that RAR identity user equal new identity user and I'm going to just pass username equal user dot username and email is equal user dot username fine you're not going to password to it why because we are going to create the user and let my user manager to Hash the password and store it in the database in a secure way how by using user manager Dot create a sync and I'm going to pass my identity user to it and then it accepts the password which is user dot password it is coming from our model and because it is a sync I need to evade it first and I'm going to put the result in our results let me check what it is returning it is returning the identity result and what is inside the identity results error succeeded okay I'm going to return this one which means that if the user is created successfully it is going to return true otherwise it is going to return false fine uh let's build the application and be sure that it is running we have an issue here here we have a register user but it is not returning anything fine I need to create a Constructor and inject our alt Services here but for injecting out Services we need to create an interface how can we do that just go to the class click control period or just click on this brush and extract interface select the members that you want to extract and click on OK it is going to create I out Services exactly in the place that you have the class let's go back to the controller now I'm going to inject IELTS service and I'm going to call it alt service and let's create a field for that and create a field for me and then return as a alt service dot register user and I'm just passing the user tweets let's run the application and see what will happen using.net wrong is running let's open our Swagger we have alts for get and post for the post is for creating a user I'm going to call it test at sign gmail.com and for the password I'm going to use password let's execute it and see oh we have some issues let's check what we forgot it says that we have one service here which is not registered which is correct let's go back to the services here I need to register this service using Builder dot Services dot at transient I outservice should be returning out service then be inject it fine let's build the application again and run it and go back to Swagger and just execute it once more now it is returning true which means that our user with username test assign gmail.com and with this password is generated let's go back to the database and validate that here if I just open asp.net users I can see that this user is generated for me fine let's go back and implement the login let's close everything go to the controller and I'm going to just evade outservice.log in the user we don't have any implementation for that let's create one generate method login fine we have login here let's go back to the service and in the service it will start nagging that you don't implement the interface completely let's Implement that let's move it down and add a scene here I'm not sure what I'm going to return let's stick to the task for now in asp.net identity first you need to get the user from database and after that check the password because you don't know how asp.net identity is going to Hash the password and a story then you cannot even compare it you need to pass everything to it trust it and just get the result let's get the identity user first where identity user is equal user manager dot find user by email async and let's pass the email come on why it is like that let's pass the email which is user dot username and for login I'm going to check if what we are receiving is null or not then if identity user is null just return false okay now I know that I'm going to return Bool and let's just click on this one and full login up which means that it is going to create this method for me in the interface yes and let's go to the interface I don't want this login let's go back to the out service it is going to return false now we need to check if the password is correct or not how using user manager Dot checkpassword async and it is accepting identity user and the password which is coming from the inputs user that I'm sending that password and because it is a sync we need to return a date uh let's see it is telling me that it is a task exactly I need to evade here as well now I just logged in my user let's go back to the alt controller we have the result here let's get the result the result call and then let's say uh if result equal true which means if user is logged in successfully return okay and maybe something like done otherwise return not okay bad request yes and now I know that I need to return I action results and maybe we don't need to have result here maybe we can just put it inside the if just to be sure create and we can change this one as well to task I action result and return an OK objects fine I need to give this method some specific roles for example here for the post I'm going to use register with capital r and for the gets I really want to use login fine and let me change it a bit for example here I can say if modulus state that is valid if it is not let's return a bad request it is not a proper way to checking that I'm just showing you how to do that and here for the register we are going to return a Boolean and let's check it for the register if user is registered correctly just return okay and tell it successfully done otherwise return bad request and tell something went wrong or something like that let's try it again and go to Swagger I can see that for the host I have registered let's register with a repetitive email address which is test at sign gmail.com and password is not important let's click on register I can see that it is returning a respond 400 something went wrong I know because the password the sorry the username already exists let's change it to test one and the password let's select the password and execute it and now it says successfully done and for login let's check if we can log in or not let's try it test at sign gmail.com and the password should be password great and let's execute it okay it is my fault it is telling me that you are sending something inside the body but you are using get method which is not correct we need to change it to http post foreign it was a stupid mistake let's run it again go back to the Swagger press F5 now both of them are post and let's check how we can try it test at sign gmail.com and the password and execute and see it says done which is uh everything is correct but if I just add one number at the end of the password and execute it again it will show response status 400 bad request something went wrong it is correct I know that I have a login system I have a register system for the users now it is time to add authentication and authorization to our web API and use Json web token to do this job for me imagine we have one more controller here and let me just call it test controller created for API empty one and call it test and it is just going to return uh for HTTP post method http for HTTP get method I'm going to create a really simple one public async and maybe even not a thing public a string get and it is just going to return you hit me we just want to be sure that this controller can or cannot be called when we are logged in or not if I just run the application go to the Swagger refresh it and run it you hit me okay fine but what if we want this one to be available and visible just to authenticated users easily you need to add authorize attributes on the class level or maybe you can add it to the method lever and you need to go to the program.cs file and add app.use authentication be sure that always put use authentication before calling the authorization but now if we run our application we will face an error because we need to tell asp.net engine to how to authenticate and authorize this code first let's tell Builder dot Services dot add authentication and it should have some options options yes and semicolon at the end for the options we need to tell that what is the scheme for default authentication and for the challenges for the default authentication scheme I'm going to use JWT uh we don't have it here I'm going to use JWT barrier default sorry jwc period default we need to install it let's go to the package Management console we need to specify the Builder that we want to use and we are going to use JWT let's install the package first by typing JWT I guess the first one the third one is asp.net core authentication JWT Bearer and let's select the correct version fine and go back to the code I'm going to use JWT mirror defaults dot authentication scheme it is what I am going to use here but we need to add another option here for challenges options dot default challenge scheme I'm going to use exactly the same one this JWT beer default scheme here as well and let's build it oh it should be JWT JWT find it showing an error because I have the code in the running mode and let's try it again yeah build successfully now we have configured authentication it is time to configure our Json web token to be our Builder how at the end of that before the semicolon I am going to add uh JWT Json laptop and Bearer and we are going to add an option to it and the option will have token validation parameters let's instantiate it oh this one is a bit too long let's add the using and this one is nicer like that but we are going to check we are going to validate our actor first and we are going to say yes validate the actor then we are going to validate the issuer yes we need to validate the audience yes by default and it is the best practice that we are following and we are validate uh we are checking the expiry required expired time true we need to be sure that our token is not tempered then we need to validate the uh we need to validate the signature as well validate signing keys true and we can validate what we can validate I guess it is enough and we should tell that if we are going to check the issuer and audience what are the valid issuers and audience uh Delete issuer is equal something I'm not sure what and valid audience is equal something else we have some variables here we have some strings but I'm going to read them from config let's go to the upsetting.json I'm going to create another section here for JWT we need to pass a key this key is the secret that all the encryptions is going to be based on that uh usually I use a guid plus something else here just for the Simplicity I'm going to create a new guid copied and paste it here and remove the extra information that I don't like okay for the issuer and audience I'm going to check my launch application and copy the URL that we are using and paste them here and here great now I need to use Builder dot configuration that's get section it was JWT and then let me copy and paste it to be sure that it is not showing an error in runtime and the other one is for audience let me copy the audience and paste it here Navi configure Json dev2 can to act as our Builder now we need to generate the token and give it to the client and client should put it always in the header of the request and JWT will validate it and let the request to be passed let me close everything let me save it and close it let's go to the controller and out controller here in the login I am going to check if the user can log in I'm going to get the uh Json web token a string where token the string is equal outservice.generate tokenstring based on my user let's generate it all right and let's go to the services I have it in the services but it should be a string and in the alt it is going to start nagging that I'm not implementing a method let's implement this method as well but how we are going to do that the first thing that we need to create here is the token how to create the token and return it let's return let's create a token a string token string is equal JWT tokenhandler dot write token I should near it dots write token and then I'm going to return this token string but for generating the token I need to pass some information to that what is the information security token I need to pass a security token to the Json security token Handler okay let's call it security token and create a variable for that I'm going to generate a local variable fine and new it here new security token and let's see what should I pass to the security token it says that okay it is an abstract class and you cannot instantiate out of that then let's try JWT security token fine it is what I want and let's check the parameters it accepts header payload payload or a lot of things let me see first I want to pass claims I'm going to create claims claims are some information that you can place inside your token and how to do that by just generating a list of claims list of claims yes and here we can have new claim and in the claim we have the claim type for example here for claim type we can have email and for the email it is the user email which is the username we can have another one for example it should be Capital C yes it should be capital c e s and for the other one we can pass the row for example here we want to say all users have admin role okay it is the claims that we have what else do we need here in the configuration of JWT mirror reset that we have issued audience and expired edit let's pass it for example expires it is going to expire in 16 minutes then date time that's now that's add minutes 16 in an hour and be sure for the issuer I need to get the configuration yeah I will do it a bit later for the audience I need to get the configuration again and what else we are going to check the signing credential then we need to have a signing credentials as well and the signing credential the value that we want to have is signing credential okay let's generate a local for this one for signing credentials fine I'm going to implement this one let's go back to the Constructor I configuration and let's call it config and create a field for this one go back here we have config.get section fine and let's copy and paste it from here get section for issuer and get section 4 audience as well like that and now the most important part the signing credential is responsible to be sure that our JWT or Json web token is not tempered on the client side by the client how by using a key and encrypt based on the key that we have how let's see new signing credential and it accepts a security key and an algorithm for the security key let's just create security key and for the algorithm we have let's see what algorithm do we have security algorithm the suggestion is using h m a s h a 200 sorry 512 signature yeah and for the security key it should be a local again oops this one is not something that I want it should be the secure from the type security key and new security key and we cannot generate that because it is abstract okay let's see what kind of security key do we have yes symmetric security key we need to have a symmetric security key and let's change the variable type to bar and let's see it needs to have a byte array and key I have the key here and it should be key but how to convert it to byte of arrays using encoding encoding dot utf-8 dot gets bytes fine and I guess we are fine to test our application the reason that I didn't start from writing from top to bottom was that I cannot memorize everything I just know that we have a JWT security token Handler which we need to write a token and after that you know I cannot memorize this it tells me that it needs an input I create the input and for the input I will check it and I will see that I need to create some other variables I'm creating them assigning value to them and it is all I can memorize let's see where and we are returning a token a string okay let's see we have the token and we are returning the token yes to the alt controller Let's see we have this one and user what is the issue here alt service is null here why it is now because we need to open a curly bracket here and we have the token string let's just pass it to the users like that it is nasty but just for the sake of this demo and let's run the code update the Swagger try to execute it for the test as you can see it is an authorized error let's login and see if we have the bidder or not it is test at sign gmail.com and the password should be password let's execute it wow it is generating this token and returning it back to me let's copy it now we want to test our application how can we test this one and this builder for Swagger there are some extensions that you can authenticate using swagger but it is waste of time I use PostNet and in the postman I'm just creating a get request let me go to Swagger again this is the place that I'm going to sending my request to and we have authorization Tab and we need to select the type here is mirror token and let's go back to the Swagger and copy our mirror and paste it here and send the request and let's see unauthorized why let me check it let's check it and see what is wrong here okay in the alt service uh where is my out service yeah in the out service we are doing everything correctly we are generating the secure key and we are passing the secure key here and in the program that CS okay found it we haven't told JWT beer what is our key uh issue signing key and we need to pass it to the issue signing key we are going to tell it that it is a new the type of key that we used there was a symmetry secure key we need to use it here again uh writing it let's just copying it it was symmetry security key yeah let's copy it and paste it here and we need to get the key foreign using key yeah we forgot this part we registered valid issuer valid audience but we forgot issuer signing key but we are registering here in this configuration we should have exactly here in the security token because it is going to generate our token based on this specifications uh can you let me run it again go back to my Postman and send the request yes you hit me because the mirror is working by changing the token if I adjust one at the end of that and send it you see that it is unauthorized let me go back and send it again yes we can hit that one okay it was all I prepared for today's video if you have any questions about JWT the payload identity just let me know in the comments below and do not forget to like this video And subscribe to my channel
Info
Channel: Foad Alavi
Views: 12,056
Rating: undefined out of 5
Keywords: Foad alavi, C#, .NET CORE, Web API, ASP .NET, Test, XUNIT, SQL, SQl Server, tutorial, For Beginners, web api, .net core web API, jwt, jwt token authentication web api, identity, asp.net core identity - authentication & authorization, asp.net core identity, asp.net core identity web api, json web token, asp.net core web api identity with jwt, Postman, JSON Web Tokens (JWT), c# programming, learn c#, C# tutorial
Id: 99-r3Y48SYE
Channel Id: undefined
Length: 42min 8sec (2528 seconds)
Published: Sat May 06 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.