ASP.NET 7 JWT Authentication and Role-Based Authorization | ASP.NET Web API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody in this video we are going to see what is JWT and how we can Implement using JWT in our web apis and how we can secure our web API using JWT and or zero technology so Json web token you can see that I'm inside of JS wc.io and in the introduction section it speaks about the JWT and it says that uh Json web token is an open standard that defines Compact and self-contained very for securing transmitting information between parties as a Json object so in fact this is Javascript object and you know that Json stands for JavaScript objects notations so this is really simply a Json so let me show you that what you can do uh with the jsons every Json we're talking or JW it has three different parts a header a payload and a signature and it's something like this header dot payload dot signature and for the headers there is a lot of ways of showing data like the type and the algorithm of its encoding and on payload you send the claims that you want to send and we will see all of them for example ISS issuer explains exposure time sub is subject and audience and we are we can have some custom claims that you want for example we can have public claims and private claims and we see them on our example and then we have the signature the signature isn't important to us we are just focusing on implementing JWT inside of this example so let's show let me show you that how the Json web token works when you are when you are using Json web tokens you need to have a token and you need to send it as your request header to like this you set your authorization header to Bearer Dash and your token and this is exactly what we will be implementing in this tutorial and this is how it works so as a client application in this application will send a request to oauth or our authorization server and sends the username and password and asks for the Json web token or JWT and authorization server will check and if everything is correct it will return the JWT or on the token to the client and client then will ask for the API resource using that Json web token or JWT and this is how it works and there are a lot of other introductions let's go to the libraries and let's see what libraries you can see that there are a lot of libraries and they are using the Json web token package and they're also for so many libraries and Frameworks and that's so good let's go to the first part and see that what is exactly Json web talking for example this is a the Json web token you can see that it has three different parts like a payload like header payload and signatures and you can see that everything is decoded here and we will use this website and we will decode our tokens and I will show you that so this is a little and a brief description of JWT and what is it so let's see what is the product of this video and what we will make after completing this video you will have this product and it is really in my opinion a good and a useful uh Json with token tutorial so you can see that you have a lot of things to learn and let's first let's let me show you inside of my code that I'm using some packages so I'm using microsoft.asp.netcode.identity.n Entity framework code which is really important package and it helps you to manage your authentication authorizations and then you can use microsoft.spnet code.authentication.jw to be error and we Implement our functionality using these two packages so let me show you what we will have the first thing is after implementing our project in database we have some tables that are implemented by our identity package I have explained users let me show you it is empty for now I have SMS roles which is empty and I have asp.ed user roles which has a many-to-many relation from users and roles and it is empty for no so we will Implement these seed roles and it will let me show you here inside of my codes that uh let me show you inside of static user rules it will Implement these three roles for me automatically so I will use out slash seed roles and if I execute it it receives an object you can see that it says that it succeeded through and the message is role seeding done successfully and if I go to my database and experience role select top 1000 you can see that no I have user role owner role and admin role that's all the next thing is I don't want it I can't register a user for example let's say that my username is Ahmad and last name is Tori and username is let's say for example mama uh uh Tahiri okay for the email it is at gmail .com so let's copy this username for our password and execute and it says that is Success Through message user created successfully let's check our database estimate users okay now you can see that my user is created he has username email a lot of beauty beautiful things and the first name and a last name Also let's check user roles and you can see that for this user ID I have this role ID it is because we have a default user role for everyone so let me show you that how we can use this I want to use a token so I can simply send a username and a password to request to server and ASCII token so in return of this login method I received an its success is through and I receive a message in this message I have my token let me copy this and let me go to jwt.io and decode it here I can paste that now you can see that my algorithm is hs256 type is JWT and inside of Clans or on payload I have a lot of claims for example my name or username is Mama tari my name identifier or my ID is this ID JWT ID is a unique ID for this Json web token my first name is Mama last name is Tyler and my role is use said and I have all of them you can see that this is simply decoded so how I can use this token I created four methods and for the first one we don't need any authentication and authorization but for the next three let me show you inside of my control layer what you are going to see and layer so inside of this simple controller I the first thing is a simple method without any authentication and authorization after this we have this get user rows which has authorization with a role of user so you need to have role of user in order to have access to it the next thing is get admin role and for this resource you need to have the role of admin and the last one is get on a roll and for this you need to authorize with the role of owner so this is it you need to use these roles so let me show you that in order to using this and send the authorization header or using Postman so the first thing is the slash weather forecast slash get let's send a request without any authentication okay we receive a 200 okay and for my get user role without any authentication if I send my request I receive 401 unauthorized so I send an Bearer token here and I paste the token here I let me show you that by using this token from here and let's send now it is the status of 200 that's so good because this user has the user role let's check this token for the admin we know that he hasn't as the role of admin let's import our token here and USB error token and send okay you can see that it says 403 if we don't use any token it says 401 which is unauthorized and when we use a bearer token and paste our token here this 401 changes to 4034 within it says that you are authenticated but you are forbidden from accessing to this resource and also Let's test for owner without any Authentication of course you receive 401 but if we use JW to be error and or or let's say beer token is better it's much more easier and same it says for auto you don't have access to this specific road so how we can access to them let's let me show you that I have two different methods that one of them is making a user admin and the other one is making a user owner so to making a user admin I can simply pass sorry my username what was my username so I sent my username to make add me and execute so it says that what is my response is Success Through message user is no an admin let me show you inside of user roles no my user has two rows you can see that it is one two three and f60 let's go to roles okay one two three is user and f60 is admin so my user is no admin and let's check so because we changed everything we need to log in again to so let's reset execute and receive our new token so let's decode this token you know that no I have just user but if I change my token you can see that my role is no is user and admin both and it is an array of Roads that's so good so let's go to here and check the admin access so forget admin role this time I must have access let's check yes I have access let's check our uh get owner we don't have access but let's check it send okay we don't have access to it yet but now we have access to get admin role that's so good and also the last one let me show you here the last one is make owner so we can make any user owner for example if I copy my username and paste it here inside the body of apis make owner and send it says it's true user is no an owner and let's check inside of my user roles no you can see that my user has three different roles that's so good and let's ask for another login because every time we are changing this roles our claims must be updated so let's create a new okay copy first let's decode it quickly here Ctrl a control V now you can see that for my roles I have user owner and admin and let's check to see if as I have access to owner no let's delete this and paste my new token and send okay now you can see that instead of 401 and 403 I'm I have 200 okay and let's check everything this doesn't need any authentication that's good let's check get user road we know that I have this role so I must be able to access that so then if I change one of this characters to test it would be 401 unauthorized because my token is wrong but with the right token I have access so good and forget admin roles let's check again I have access so good and forget owner role good I have access so this is just a basic example but it shows you that you can simply use this authorization with this rows for any resource you want and restrict that resource to the roles that you want and also you can use these roles here inside of the controller so all of the controller will be uh will be accessed just by the users that have these rules so this was the demo of the product of this tutorial and this is everything you want to use JWT and also I have implemented all of the codes into the GitHub repository of this tutorial and also I want to show you that I have different branches for different versions and in this tutorial you see that we will refactor our codes twice and for each of them I have another sorry I have different branches and this is because if in the future we want to update this repository you can always refer to this versions and these branches and the codes are exactly the same as when you are seeing this video for example in version one we have just six commits and in version two we have eight comments and in version three we have 10 commits but in the future we can add another branches that if you want to go to a specific branches it will be saved on the exact State and that's it so if you enjoyed this demo please like this video and leave comments for me and let me know what is your opinion about this video and also subscribe to my channel so let's start at Implement our backend projects as always we create a new project in this tutorial I'm not going to create a full stack project and it is just a web API so I directly create my project here and create a new project so for templates you can simply use C sharp from here and four project types I choose web API so this is my template asp.net core web API next and I say it is JWT security or let's say JWT art asp.net web API and SB net 7. so that's it is just a test name JWT art asp.net7 web API in Drive F let's go next and it is.net7 okay I don't need this configure yes don't enable yes yes and no and let's continue to create our project so this is my project and let's see it's folder inside of Drive F you can see this is the folder of my project and that's it so I want to initialize my project and use GitHub so let's close this for now you can for handling your git initialization you can use command lines or anything you want or even you can use Visual Studio but I use Visual Studio code and I think it's better idea so I open this project with vs code and here instead of its root I created dot git ignore and read me that MD so in git ignore I want to ignore some files I simply copy them from my GitHub and you can also copy with me so for example this is good and that is ignore so let's copy all of these and put it into that git ignore that's good and also in readme I simply say JWT out with asp.net seven web API this is it so let's open a new terminal here view terminal git init good git add Dot and git commit Dash M init this is really important to work with GitHub and version control system so this is it so my project is now using git now let's create a new let's go to my account and create a new repository new so I say your name is YouTube Dash let's copy this name from here you want to use this simply so YouTube is saying good it is public and let's make everything like it's default and create our Repository so now you can use a new repository or an existing for existing repository you can simply use these three lights so I copy this and here I paste it git remote at original this repository then git Branch Dash and Main will change the name to main that's good and you push that's your origin me and that's it this will push our code to the GitHub so let's refresh now you can see that my project is here but I want to have different branches for my different versions so let's do this now and then continue so you can simply use git branch and make a new name but I want to show you that how you can use this graphical user interface so you can simply create on this Source control here and here you have a lot of access of everything you want I simply use this you can see that you're clicking on this main here and down it shows you that a lot of options so I say I want to create a new branch and I say that what is my Branch name I say V one and I press enter so this branch is created and no I can publish this price so by clicking this publish branch this branch is you can see that it is finish so if I refresh now I have Main and Viva so this is their branching and we simply created our GitHub repository so let's for now let's minimize this Visual Studio code and go back to our visual studio and open this JW out the project that we created okay that's it so here you can see that no I have access to Main and V1 and that's so good so and this is the initialization let's start the first thing is I don't want to use this video forecast I delete it okay and also let's go to its controller and make it a little simpler so I don't need this log here I don't need this Constructor and here for this method it is an HTTP get I say that let's delete this it is much more readable this road so I say your road is get and that's so here I say that your signature is you are going to return a i action result of get and you can simply instead of these you can simply return and okay status Suite this array which is summaries we don't push our attention to this controller and we just need to show the authentication and authorization so we just simply return this array as our resource so let's say delete this line okay that's so good and that's it so this is the controller so let's create a new uh commit so I show you that you can see here you have this so it shows you that you have these changes you deleted this stage and actually deleted this stage so refactor weather resources and and you can commit a state and push so you can use each one I can simply use commit State and push and that's it so let's go to the GitHub and now you can see that okay we won't have recent pushes you can see that in main branch I have uh I have this video forecast but if I go to V1 it must be deleted yes you can see that it is deleted that's all good and also in controller let's check yes you can see that it is now clean and we are working on the swivel branch and that's it so and now we are aware of what are we doing inside of our Branch then we can make a pull request for it so for now let's close weather forecast and continue to implement our project the first thing is we need to have some packages because let's close everything and this okay the first thing is we need to use some packages in order to use identity and use our database let me show you what we are going to use here the first thing is we need to use microsoft.acnetcode.authentication.jw to be error to handle our JWT tokens the next thing is microsoft.acnetcore.identity.entify Network core because we are going to use identity package and it also installs Entity framework call for us this is so important package and you need to be uh familiar with it and you can see that it has 113 million downloads and also we use anti-federal code.sql server and it's very recorder tools let's install all of them so I copy the name from here and let's go to the dependencies right click management packages so browse in a style let's search okay microsoft.ace minute core authentication jwtbr install okay I accept and that's it so next is identity.t framework or this is really important so let's paste the name and search for it microsoft.asp.netcore.identity dot Entity framework in install Okay I accept good the next thing is SQL Server we need to use SQL Server so let's paste it here at search Microsoft dot entity definable code.cl server that's it okay I accept so good the last one is Microsoft that anything will call the tools and you know that this helps us to have migration using EF core so Microsoft and different recorder tools is good install okay I accept that's good so let's see the install now you can see that I have all of them and also I have Switchback that is minute core and Microsoft that has been recorded open API which was installed before this so we have four packages now and you can simply check them here you can also double click on jwto using name of your project and you can see all of there here that's so good so now we installed our packages the next thing is we need to have our application DB context and its configuration so let's create a new folder named core uh I use this core and you can use anything without folders but you know that it's better idea to have folders for everything and sometimes also you can use different class Library projects for them I simply use different folders and I think it is better idea for our tutorials and we can because I'm using different versions on other tutorials you can simply say what you want and we can simply refactor them so inside of core I create a new folder name DB context and inside of it I create add a new class of application DB context application DB context okay so this Theory context should inherit from Identity DB context let's press let's here press Ctrl dot it says that using Microsoft that is my code.identity.activen our core yes that's it and let's first control that to create its Constructor automatically and that's it let's change this to generic and copy this from here I assume you are familiar because we have done all of this on our previous works but if you have any a question asked on the comments and we can create different videos just for this part so this is the only configuration we need for now this is our context the next thing is we need to use our connection is sitting inside a program.cs and you saw that it is a best practice to create them inside of app setting instead of hard coding in program so let's create it instead of app setting.json after this I create a connection as strings which is an array and I say if you have a local and here we simply can say that your server is Dot and it's local so your database you can use any name you want for example this I can use this name of JWT odd asp.net half the API DB any name you want is good I use this one simply so after this we need to use user passport I can simply use trusted connection because I'm local trusted connection I'm using my local database and also I say trust server certificate is true that's it and this is just the the configuration we need for our database so let's go to the program that CS let's do some cleanup delete this delete this delete this and that's it let's press enter here because this is for our pipeline so let's have a comment and that we don't want to work with it let's add our DV so we simply say that Builder that sorry Services dot at ADB contacts with application DB context this is it and it has some options and inside of options we can simply use that out connection string equals to Builder dot configurations dot yet connection is steering of my local this is the connection essay and we can say that options that use SQL server with this connection is thing that's it and also because we are going to use our identity you saw that let me show you inside of application we inherited from Identity DB context and we need to configure it so let's do all of our configurations and add because the this can be a little complicated to you I divide them to different sections for example the first section is at identity next we need to config our identity and also we need to add oops we need to add our authentication and JWT Bearer so now you know that this is different sections of what you want to use so the first thing is using identity we can say simply is Builder that Services let's go to the next line to be more readable dot add an identity any identity you want to use a t user and troll so for user we can use identity user and also for role we can use identity rule this is the first line for the next line we need to add Entity framework stores and what we need to use we need to use application DB context so we need to use application DB context as our stores and also let's add a default token providers it is required for using in our identity this is all of configuration for adding identity next thing is configuring our identity so you can simply config everything we want for example builder.services that configure and we can have some identity options that's it so we have some options and for them we can say that for options we can use for example for password dot require learn can be for example 8 or 10 or 11 or anything you want also we can have options that password that for example required digits can be false also we can have options of password we have a lot of options for example after this we can use required lowercase and uppercase for example lowercase files and uppercase files it suggested for me automatically that's good and also we can use options dot password dot let's say require non-alphymetric files and also let's have another one for example for sign in we have required you can see I have required confirm phone number confirm account confirm email I for example I say Comfort email is false and also a lot of them or accessible I just want to show you the example and this is it so you can have any options for example let's say that options that you have access to logout DOT sign in that password and you can see that you have to use a claim identity you have a lot of options so in stores tokens this is it so let's delete this line and this is for our config identity next thing is we need to configure our authentication and JW to be error so let's add it we say be clear.services okay let's go to the next line to be more readable at authentication and as always after this we need to add JWT br and that's it and for this we can have different configurations for example for add authentication we can receive some options and now you can see the structure of it and we say that for options we can use for example options Dot default schema can be a JWT be aware JWT defaults Dot authentication schema let's copy two time also we can use for because this is default it can be for everything but I will show you that there are a lot of options like default authentications and also challenge so default challenges schema so for all of them we just use jwtbr defaults.authentication schema and then you can change it but now you are familiar that we have some of these options here and it's enough so 4jwbr let's have some options you can have a lot of options here for example options Dot save token is true uh it's better to not cover all of them because it takes a long time and we can simply search for them later so options.save token is true options that require https metadata can be files and the most important thing is options Dot so again validation parameters is a new validation parameters but let's delete this part and using control dot using it is much more better you can see that no it's more readable so inside of this new token parameters we say that you need to validate issue is true and also you need to validate the audience is true and you're valid issue must be in some IPI let me write everything to see and then I show you valid issue and also you need to valid audience something and then we need to use issuer signing key so for this valid issue we want to use some strings and it's better to use them here so let's add another part here inside of this app setting and after this connection is reading we create a new JWT value key uh this JWT is an object and here we can have all of this so let's copy them for example for valid issuer let's copy this G and let's define it here and also let's have the valid audience and let's have it here this is better and also we need to have a secret for our key it can be anything you want you can see that I'm creating it so randomly and that's it and this is for my secret so for valid issuer I want to use the IPO This Server how can I access to it I can go to properties uh because in profiles I'm using https so this is this URL copy it is what I want so this is my valid issue and also for valid audience we can say that this is for example localhost of three dozen and you can use any if you want for your audience for example if it's a react local react project is almost a lot of time it is three thousand that's it so I have valid issuer valid audience and secret and how I can access to them in fact let's close the application due context online setting in fact it's too easy we must access to our configurations so for this we can simply say that build that configuration of JWT and validation and let's copy this also for audience we can say that Builder that configuration.jwt and valid audience so it would be read from that file and for issue signing key and we can use new symmetric security key of encoding that UTS eight Dot get bytes of that secret that secret would be Builder Dot configurations of JWT let's copy the name from there upsetting so it is Secret that's it so now I have access to all of them here and this is let's have another semicolon here this is all of configurations I want let's close it let's delete some despite the space Also before this authorization I need to use app dot use authentication that's it now I have all of my configurations and let's close everything and check my database connection so let you need to open [Music] on other window view other window package manager console you need to use at migration of let's say init and test it okay let's say update database it seems that we don't have any error that's good it is migrating and it's done let's open our database connect so JWT odds that's good you can see that we have a lot of tables like role claims roles users and a lot of them let's check roles it is empty let's check user roles it is empty let's check users it is empty that's it this is all of the tables we have and Let's uh go here and let's have another commit so application DB context good migrations uh okay Implement DB and identity so we estaged everything that's good let's commit and push that's it so this is the part that we created all of our programs yes the next thing is we need to use some details and then Implement our controller of authentication so inside of code I create a new folder named details and for my details I want to have let's create a new class of register dto that's it inside of it I want to have some different uh props like a string of username and for this I want to have an annotation of require D and I must say that let's copy this name from here username is required and this must be message and our message is username is required Also let's copy this and this time for username next thing is my email and I say your error is email is required let's copy again and also let's receive my password in this video and we say password is required this is registered dto let's copy this because it is exactly the same like this video Let's copy all of them and create another video ad a login dto I'm creating this details first so you can see this overall structure so in login I don't need this email I just want to use a username and my password that's it so let's close login and register Also let's create a new dto and because I want to update my permission so I say update permission dto you will see what is this dto and for this video I just want to use my user so let's delete all of this Ctrl s and that's good so I created three different details login detail with username password register detail with using an email and password and update permission dto with just username this is all of them also let's create another folder here so inside of core I create a new folder name other objects and here I create a new class its middle name is static user roles and I want to have some roles and our roles must be a string but in order to avoid any some errors and typing problems I simply use a static class here and I create some some string inside of it and we can simply use that so you will see how good it is so we create some string and this string must be cons for so public a string of owner is owner this is it this is my first role let's copy this two times this is admin and this is user so let's copy admin and copy user no everywhere we can simply use a static user rules that owner and we avoid a lot of our typing issues and that's so good so this is a static user roles I think for the files it's it is completed and let's create our final thing which is our controller so let's create it so inside of control layers we have the forecast we don't want to work with it right now let's create a new controller and add controller API and before this let's check uh I know that you think this may be a little boring but in fact it's too important to have a big uh sorry to have a little commits so let's add a comment you can see that I have a lot of changes for example I created these videos first let's save everything okay for this details say all of them and also the stage this so I say add detios and a static rules let's commit and push and let's check the so let's go to the V1 branch and refresh okay no you can see that inside of this branch of V1 we have four commits and this is really important and you must know that this is an Enterprise level working with GitHub this is really so important so I'm covering this inside of this video and by the way if you think this is a slow tutorial you can simply increase the speed of your video player in YouTube and watch with uh faster speed so this is it and let's continue so we committed everything now it's time to create our controller uncontrollers add a new controller API API controller empty your name is auth controller and see it and in this controller we need to use some different managers and let me explain it better we need to work with our roles and our users and we need to do a lot of operations like login like register like check our password so for them we have two good tools which are coming from our identity and let's use them for example the first thing is private read only of a user oops user manager let's press Ctrl dot it says that using Microsoft and different local.identity that's good and this is you this receives you can see it receives a t user so I use my identity user for it and it is a user manager and we need to inject it inside of our Constructor so I press Ctrl Dot and say generate Constructor with this and if you're asking what is this this is related to dependency injections and if you are not familiar you create a new video later for them just let me know in our comments so this is the first thing the next thing is we want to have a private thread only another good tool which is a role manager Ah that's so good so inside of this role manager we let me show you again we're receiving a hero so I simply use my identity role for it it is a role manager it needs to be injected so let's press Ctrl Dot and choose add parameters okay no it receives here and it says that on the road manager which is this private only is this role manager also we need to use the configurations inside of app settings so let's receive using private on layout I configuration of underline configuration and lets us inject these using add parameters I'm pressing Ctrl Dot and this week shows me add parameters that's good so I have a configuration and underline configuration is configuration that's it this is all of the tools I needed the next thing is we need to have some different roles for example I want to have a road for seeding my rules to database so we can simply use an HTTP post and let's have a road for it so in this road we simply say seed rules that's it and let's create a public async task it is a good idea to use async of I action result of seed rules and that's it so in this uh function we can simply use the role manager and we say the weight of role manager dot create async and this function receives an identity role so we need to create a new identity role and this identity role let me show you here you can see that it receives a string of role name so we created that static role name for this so let's use our static user roles static why it is not recognized let's check it okay aesthetic user rules let's copy the name and here it's a user no dot for example the first thing is I want to add user that's it so let's copy it twice I said also you need to use admin and you need to add owner that's it and after that we simply return okay and we say that rule CD done successfully and that's it but let me show you a beautiful thing here because it will always tries to create this create AC we can't avoid it and we can simply say that use some flags and let me show you that how we can do this for so we can create new Boolean with name of is uh owner role exists and we can a weight of we have different functions inside of our user manager role manager and here we can use role exists async uh static user roles dot owner so in this uh role exists returns a Boolean and it says that if it exists or not let's copy it two times and for this we can say this is for admin role and this is an admin and the last one is for other user and here we say it is user so we check that owner and admin and roles the user is exist or not and then we say that if is on a role exists and is admin role exists and is user rule exists simply you can return an okay and say that rules seeding is already done else you can simply sit them all and return this okay so I think this is good for now and let's check this function so let's save everything and start our project in the meanwhile let's check database so for roles let's see roles it is empty that's good so let's create them using seed roll try execute it's either rule seeing done successfully let's check okay congratulations we have three roles in my database so you can see we have admin user owners let's try it again and see the results so I execute again it says that role seeding is already done that's so good and it says that it is here so it shakes and it saw that all of them are exist that's so good let's minimize the seed roads and go to the next part so the next thing is of course we need to register our user then login so let's create a new method of http uh http oops HTTP post okay uh let's create a road for it and the first thing is this road is four of course when you first need to register our user then he can log in so the road would be registered that's it so let's create a public a Sim task of I action result of register and what you are going to because what we are going to receive we created uh let's say from body we created a dto for register so we say register the Tor register T2 is received from our body and we work on this so the first thing is we need to check if the username is duplicated or not so we say that that is exists user you can see that I'm using a good self defining names and his existing user is a good name so I simply say Evita I want to use the user manager dot find bye you can see I have found by email ID login and name I use by name async because I want to use my username so let's say that you are checking registered dto dot username so we you need to check this username that's it and if is existing user returns a user it would not be null so if you say if it is not null simply return a bad request and you must say that the user name already exists and that's it so if user is not null if this exist user is not it means that our username is not in database and we can create them so let's create a new identity user identity user uh new user new identity user and for this user I say your email is registered detail.email and your username is registered to that username and let's add a security stamp which must be a geoid DOT new gui.2s3 and that's it so we created a new identity user here next thing is we need to use create async and create this user and add the password the hash password so we say that that of create user result is a weight of underline user manager Dot create a sync the first thing is it receives a user so let's pass the new user and also it needs to receive the password and then it will hash it automatically so let's say that the password is my dto.password so we say register dto password is your second input then we check this result and we say that if and this create is a result that succeeded so we said if succeeded is false it means that we have an error so we need to return these errors to user so we can see that what is the problem so let's create a beautiful esteem for it and I say error a steering equals to user creation food oh because and that's it so then we have this uh creation user result will have some errors which is an array so we can simply use a 4-H for it so we can use for each and we say that for varro any error in inside its collection is create user result dot errors you can see that this error is error and here simply we can add them to my error string so a resting is plus equals to this delimiter and let's add it error.d description that's it and after this four each we can simply return a bad request of this error stream else if so if we don't have any error here and if it is succeed we can simply add a role to it so we can simply say user manager dot add to roll AC and let me show you the first input is the user so user is this new user which is created in our database and for the role we can use that as static user roles dot user by using this line let me add a comment for it and default user roll to all users you can see that by using this uh line we create a default user rule for all of my users and then we can simply return an OK and we say user created successfully so user created successfully that's good so let's stop and check everything so I can simply use a breakpoint here to show you okay so let's go to register and let's stick with all of this default value and check so we say that if it's come here you can see I have registered dto a string string is three let's go to the next line okay is this is exist so there is not that good let's continue so it creates a new user that's good let's press f11 so what okay you can see that sucks it's false so let's continue and see the results and it is 400 which is bad request it's a user creation failed because password must be at least eight characters where is this coming from let's go to program CS this is coming from here because you said that your password length must be at least eight and you can config all of them here so you can see that I want to use let's say a minimum of four or three is good for me because this is just a sample let's start again and use this register so let's send these default values string string a string continue continue okay this time it is succeeded that's so good so let's delete our point and continue and it says that user created successfully let's check on database so asp.net users okay my user is created a string that's good that's it and let's check asp.net user roles so for this user ID this role ID is created this is many to many and we can create some different roles for our users that's so good so I think our register is working correctly let's minimize it and go to the next part which is we need I need another road for our login so let's do it let's do it and let's create HTTP pause and we need to use a road for it of course it must be a login or you can use a sign up sign up sign or any name you want you can simply use register and log in here so for the login I want to create a publish AC a new task and this task will return again or action results simply so I say this name must be login and this time we receive from our body we created the login detail on the initial initial part of this video so we receive a login detail let me remember you quickly this was registered username password email and this was login username and password that's it so let's close and close and close program and I don't want them anymore so we're receiving this login and let's say that we want to check that off user so we need to check the password of our data is because our the user so we can simply say that well user is a weight of Mandela user manager Dot fine by name again because we are using username and we can simply use this login dto dot user so if the user is null or we don't need this calibrations you can simply because we just need to online we'll return an unauthorized and this simply return invalid credentials we don't say that your username is wrong or password is wrong for security reasons and we simply return on authorized so this is the first part after this if we don't return unauthorized we say that is password correct is elevator underline user manager dot check password AC okay let me show you the first input is my user that I can find it here but using find my name and the next thing is my password this password is coming from login dto dot password and this method will check this input login password read the password which is said you know database and it will configure them automatically and that is so good and also if and not self is password correct so if our password is not correct we can simply return this unauthorized again so let's copy this because it's exactly the same no if our username is wrong and it is not exist in database or our password is not matches the username we simply return unauthorized that's it then if we don't return anything it means that our user is existing database and its password matches so let's grab the roles and we say that my user rules is we have a lot of good functions in user manager and role manager for example here we want to use get roles async of this user and that's it the next thing is we need to use some claims I don't want to speak about it claims so much in this video we can create a new video just for it and in this video our focus is just for overall functionalities and JWT or Json web token so let's uh create them and then in our next video we can talk about climbs so I have all of my roles here and I need a claim for all of them so let's create a list of Clan for example a lot of oath claims equals to a new list of claim and for this new list let's have a lot of claims so for example I want to have a claim for my username and let's copy two times so you can see that we can have a lot of claims for so the next thing is I want to have a claim type Dot let me show you we have a lot of Clans you can see there are all of these available so I simply say that green types that name and it would be my user Dot username this is the first one and the next thing is I want to have a cling types dot name identifier which is my ID and I say user.ite that's it and also let's have a JWT ID let's have a unique ID for fjwc it can be used on different projects I don't want to speak about it I simply want to use it here so you are you will be familiar when you see on the next tutorials so let's use uid.ud.to string we create a new and uid here for JWT ID and this is the initial articulate after this we want to mess we may have different roles so we need to use for each because this is this user zeroes is an I list so you can use a four each and we say that for each user roll in its collection what is its collection its collection is user roles and we say that for each of them you need to add so out claims dot add you need to add again a new claim and what is this claim so your claim key is claimed types that role don't forget to use describe tablet rule this is really important and also we say that this is the user row that's it so for each of them we add a new claim for my role into my art clips this is the next part and then we need to change this all of this claims into token but because it will be another functionality we create a new method for it and we call it here so let's say that battle my token and string token is generate new Json web token that's it and this Json web token needs to receive the odd claims and then we can simply return and okay with this token this is it now we need to create this function so let's create a new function and let's copy this name and what is this uh generate new website as generate new Json web talking it doesn't need HTTP Road HTTP method and raw because it's just a simple private function so let's create just a simple uh okay we are inside of this method we need to go next okay let's create a private and the return type of this is a string so we say a string of generate new Json web token it is receiving this claim and you know that this is a list of claim so we can simply say that you are receiving a list of claim and the name is claims that's it so inside of this we need to create some new token let me show you inside of this program.cs here we say that your token validation parameters is this and you need to use these so let me copy all of them from here because I want to use them and go here to out controller I comment all of them okay so here we need to have some different things like security keys and for example issuer and audience so first let's create this uh symmetry key so let I exactly copy this line from my programs yes and I say VAR oath secret I create this secret here I say this is a new symmetric security key up encoding.utf.getbysofbuilder.configuration.jwt secret and this time this Builder would not work because this Builder now here is underline configuration inside of controller so instead of being there we can simply use underlined configuration I intentionally copy this from program CS to show you that this underlying configuration is exactly the same that we have there and that's so good so let's delete this and this is underline configuration of JWT secret so there we had access of Builder configuration and here we just use underline configuration so this was for this the next thing is we need to create a token object so let's create a token object and this is a new JWT security token that's it so inside of this security token we have some keys and values so the next thing is it's issuer who is this issuer exactly again configuration of now you can see that I'm exactly using the same so is issuer is exactly this key that's good and also I need some audience who is this audience is under like configuration of valid audience which is this that's so good and let's use another thing for example when this token will expires I can say daytime that no Dot at hours and I say in one hours it would be expires and we need to use claims so for claims we receive our claims from this input that's so good and also let's have a signing credential so for this signing credential we need to use a new signing credentials of this art secret and we need to have let me show you this overload a bit we need to use a string of digest and ensure the new sense of the signing credential class so here we need to use uh the algorithm of security so I use security algorithms H Mac of 200 56 and that's it so this is my token object no I don't need them I could delete them so you saw that we created this token object and now we can use it so let's grab the string of token from it and we say that string off token is a new Json security Json security oh sorry it's not recognized it is JWT security token this is secure token Handler Dot write token of this token object that's it now we can simply return this token and that's it so inside of generate new Json web token we created a string of token using issuer and valid issuer and audience and expires claims and signing credentials you don't need to learn all of them you can simply use copy pasting them on your next project and that's it so this is generate new Json web token so let's minimize this and minimize this and let's check so stop and start so you know that we created a database let's open it okay we created a string string now we can check it okay so let's check in login I say that a string string is good let's check what he said it returns and Jada is talking that's so good let's see that then we don't have the username what happened for example is sync one for username it says invite credentials let's check that username is true and the password is wrong also invite credentials but if username and password is true we return JWT token so let me show you what is this JWT token I will open a new uh bro Tab and I say JWT dot IO let's check our token inside of this website it shows you that every token has three different parts a header a payload and a signature and let's paste our token here now you can see that my token had three different headers it either says that type is JWT algorithm is HS 256 this is my data and this is my signature we just need to focus on this data let me copy this from here and show you Json visualizer invalid okay let's copy all of them from here paste okay now you can see that I have some keys and some values for example for this name is string it's name identifier or ID is this you can see it starts with eight four six let me show you 846 the last is ff1 so you can see this is exactly my user id then we have jwc ID and unique ID for this Json web token and its role is used as a wood expiration time and issue a an audience and issuer are already here and that's so good so this is my token uh no I can't work with it no let me show you that how we can use this token so let's stop everything and let's check our changes Soviet programs yes and odd controller so let's have a commit in V1 we say that okay add and add okay uh implement basic art in art controller and let's stage commit and push that so let's check okay go to V1 okay no this is my final commit dependent basic oh you can see that we added this odd controller and also we change these options to three this is the beauty of using guitar so so far so good so let's go to the another to the other with the forecast controller here I want to show you how you can use this authorization and role based authorization in fact so this is a get okay this is a get method so you can simply use it let me start I'll show you so this is Art controller let's minimize it and this is weather forecast controller so here I have just a simple yet method let's try it and we'll return a list of these names that's good but in in order to using let me stop in order to using authentication authorization we need to use an annotation so here I can add another annotation uh it says that you can use authorize and this authorize say that this method needs to be authorized and you need to send a Json with tokens to it because we added all of our required configurations here we said that you need to add authentication and add JW to be error and also we said that you need to both use you need to use both use authentication and use authorization and that's good so when we are using this authorize we can simply say what is your role so let me show you that for the first one I say that this roles can be a static user Road dot user what this means this means that any Json web tokens that you are using must have this role inside of it that's it so let's change the name of get uh users role so let's change the name of this also to user role and let's say and also let's create another for admins and owners so this one is for get users the next thing is get oh admin let's delete this user to user uh the next thing is get admin role oops Yeah problem oh this uh okay let's do it again a certificate of get user role the name of function is get you zero okay and its authorization is user that's good let's do it again okay for the next one we say get admin role and the name is get admin role and its authorization is starting to use the rules that add me let's copy another one and yes owner role and here it must has the owners that's it so now we have different functions with different authorizations now you can see that any user must have this role in order to access Let's test and start our project so for this get method we don't have any authorizations so we receive everything but let me show you with get user roles if I execute I return 401 it says that you cannot access to this resource also for this we don't have access okay and for this we don't have access that's good we need to send the header to our request we can configure them instead of swagger but the most standard way is using Postman let me show you I open my Postman okay I here want to create a new request so let's check everything and the first thing is this simple method I use it and I say that the first thing is this local when you want to use authorization you can use these headers here but easiest way is using this authorization tab here you can use it no alt and send request this slash gate is okay it's normal let's copy the next one and the next one is get user rolls let's copy it line this line from here it's you are let's create a new request let's minimize this part okay and here for the authorization for no let's say no outstand we receive 401 and also let's copy the next one which is admin role with no authorization [Music] good Percy 401 Also let's copy the next the last one which is owner so we can test everything related to our different roles for authorizations use no art okay now you can see that the first one is okay but for the next ones we don't have access and we receive 401 unauthorized and this one and this one we need to send a Json we're talking to our server how we can do this it is so simple Let's uh first we register then we log in so we registered now we can use a string string and let's create a Json tokens okay we received it let's copy go to postman here I want to send my Json web token so let me show you you can simply use BR token here and paste all of your tokens here you can see that let's send no you can see that for this get user role I access and I see 200 it means that I have access let me show you if I use no authentication I don't have access that's good I received 401 and if I use beer token and I paste my token here I have access to it that's so good now let's check the others because let me show you we created different authorizations for different roles so for the get admin role we need to have admin and for the owner role we need to use owner let's check so forget admin role I again use my token so Bearer token and let's check unfortunately we received 403 let's use no oath so it says that 4 over unauthorized you don't have access but also if I use my Bearer token it receives me 403 4bidden it means that you have the access and you are authorized but you are forbidden from this resource and you don't have access to it you need to have admin role so let's check the last one and then create our functions the last one is get on a roll with no auth I don't have access it receives 401 but when I use my Bearer tokens I received 403 and that's so it means that our authorization and role-based authorization is working correctly so how we can access to them we need to give roles to our user let's do this and let's continue so let's close this weather forecast and continue to creating a lot of functions to implement uh adding roles to our users so I of course need to have another road and I want to make my you are my is not good may use it two admin we need a road for this and also we need to use a role for making our user owner in real world we don't use this online we use this owner on our database manually but this is a tutorial and I want to show you for example let's say that in an ecology you want to have seven or eight different roles you can simply use this so for admin let's create a http post what is the root for roads I say that make admin oops make it means that I need to learn tentai fingering fast so a lot of make admin and then I can use public a think of task of I action result of make admin and this is the part that I want to use this update permission D2 that we created on the first of this video so we just we need to receive the username and change its permission roles so all we can do this it is also similar into return receive this update permission dto so we received this from our body from this from our body we received update permission dto of optical Imaging dto and here firstly check the user if it exists or not so let's copy from login because it is exactly the same logic so copy from here you can see that copy pasting is a good idea a lot of time so we see that where user is available manager dot find by name async of this dto node is octave permission detail dot username and user is null we simply return a bad request this time because we say that on the next steps we can simply use an authorization here for this post and only owners and admins can access to these so they are sure that this username is exists and we don't want to use unauthorized so here we can simply say that invalid username that's it and if this username is exists we can simply use again use our user manager and we say that user manager dot add to roll AC it receives an identity user of user so we found the user and for its role we can simply use a static user roles dot admin and that's it and simply we can return an okay and we say that user is no and admin and that's it so cool so easy let's stop and also let's create the last one because this is really so like this so let's copy all of them and change them because it is equal to this uh make admin so the next thing is we want to make the user to owner so here for a HD poster make make owner with from body we receive update permanent detail that's right the user is exactly the same that's good if there is null exactly here just we say that for this user actual async we use that owner and here we return okay we say the user is now and owner that's it so let's uh save everything and test so let's start and let's test make admin so for example I say that my username is string we created this string I execute what it says user is not an admin Let's test on our roles so select 1000 ASP rules okay user rules okay now for this user ID I have two roles you can see it let's test and let's grab a new token for this user and check its access so login username is stream right password is string execute and this is my token no let's check my token inside of everything so this one is good we don't need any authentication okay so for get user row let's test my token and send it's okay because you know that my user my user has the user role already let's check the admin let's press Ctrl V and paste my token okay no that's so good you can see that I have access of 200 to get admins let's check if he has address and it has access to owners paste send no you don't have access right now we receive 403 Let's test let's go to [Music] the make owner and test it so I say for string a user is now an owner that's good let's check on database no this user has three roles that's all good and that's good so let's receive the token from my server so I say login give me a token that's good let's check this token I want to show you beautiful thing now because you know that he has no this user know as a role of user admin and owner let me show you okay this is my decoded payload you can see that for role no I have an array of admin user and owner that's so good so I have all robes let's check my token here inside the last one said no I have access to it now you can see that how cool it is so let's check our let's close Json token and let's see all of my files and folders so inside of auth controller we created API out seed roles register login make admin and make owner that's so good also we created some functions in our feeder forecast controller we created a single get without any authentication an authorization get usable with authorization of user role get admin role with the authentication of get admin role and get owner role with authentication of users that have the owner role and all work so for the last check let's do a beautiful thing I delete everything so let's go to the users let's edit top 200 because I want to delete this so delete oops choose the row delete okay Ctrl s no let's select up on those okay every user is deleted okay cancel OH Close all documents that's good so Also let's edit top 2000 rows and let's delete all of them to do our final check so let's select all our roles it's empty users empty and user roles empty now let's do the final check I stop this project and save everything close everything uh I start using https server now let's check everything I see my roles so execute good roll ceiling done successfully that's so good let's check rolls good and also let's check our register so this time I create let's say this is my simple user the name of this user can be user or Reservoir so its email is user one at gmail.com and its password is user1 let's execute user created successfully you know that any user has access to user role so let's log in with this user and we say that this is user1 and user1 execute get me token thanks copy let's go here and test the first one is okay for the next one I want to use it let's close this delete everything and paste my token and send I have access that's so good let's check get admin role delete paste this user receives 403 so good and let's check get owners 403 that's so good this user hasn't accessed anything but user no let's create another one so inside of register I create user two and use it to gmail.com and his password is user two let's execute okay is it created and for this user let's make this user add me so I say that is username is user to execute user is no an admin that's so good let's register with this user we created the registration let's login reset okay say username is user 2 and password is user to execute let's copy this token and go to postman let's check everything the first one is okay we don't have authentication let's check its token here for get users role it is working because this is the default role for everyone and also let's check admin so here let's paste my token and send that's so good you can see that I have access to this admin role authorization and it is 200 let's check that if he has access to owners it shouldn't have access let's check no you don't have access that's so good and for the final test let's create an owner so let's go to the register and let's create user3 this user3 gmail.com and password is user3 execute user created now let's make this user 3 tool owner this user3 execute user is now and owner that's so good so for user3 let's login and get reset okay so username is user 3 password is user3 and login okay I received a Json token let's copy no let's go to the auth or okay so good let's check this token for get user we know that this must have access that's so good because we have access to this get user role because every user has this default role let's check yet I've enroll and let's paste my token and let's see okay it says that 403 so I have the roles of user and owner but I don't have a role of admin so I don't have access to this type of roads that needs authorization of admin that's so good let's check our final which is yet owner and delete this token paste my new token and send uh 200 so you can see that our authentication and our authorization let me minimize everything okay you can see that all of my authentications are working correctly and let's check whether forecast controller to show you again here we use the authorizations with different roles we tested everything and now you can see that we have access to all of them also you can use this authorization here up on the top of controller and all of your controller can be under this authorization and that's so good so let's check our changes okay or controller and with the forecast stage and Stage final commit R version one and let's commit a stage and push that's so good so this is okay this is not uploaded and let's go to the GitHub and let's go to YouTube JW full on refresh go to the Vivan okay now you can see I have six commit and all of them are here and they have Commit messages this is really important for example refactor for example inside of this Implement DB and identity I I have done these changes you can see that the record is here and that is so good so the final thing is we need to create a pull request from our V1 Branch to our main so let's go to Vivan and here it says that you want to add recent pushes one minutes ago let's create a pull request okay able to match V1 from V1 to Branch me okay create for request that's it and no okay it says that we don't have any error and this branch has no conflict that let's measure pull request confirm merge okay that's so good so let's go back to our YouTube now you can see that all of my comments are here on my main branch and I have all of my comments inside of this and that's so good this is for the next part of implementing our JWT on the next part we just have some refactoring but the business logic is exactly the same and that's it uh in previous section we implemented all of our required functions and AK roads and everything we wanted and now I want just to I just want to show you that how you can refactor everything and use your branches perfectly so we created this V1 and this branch of May so the state of our current codes is inside of this V1 and we merged it into our main we can simply remain this V1 as what it is right now and create new branches so this V1 will be held for everywhere and for every time you want to use it and I want to create a new branch and work with it so let's go to here and let me show you that we have Main and we have V1 for now so for this may I want to let me show you that what I have right now inside of my vs code let's okay let's close this so this is Viva let's go to the main and you cannot see that inside of this main I simply let me show you I don't have the required configurations and changes which are on GitHub because we don't updated this local repository we can simply use the pool or get fetch but I simply use this synchronize it must receive okay now you can see that I received all of them and now if I open a new terminal and I say CLS dash one line you can see that I have access to all of them so let's close this yes so now all of my files inside of my main is updated and I can create and also I have V1 branch and I can create a new Branch from this Main and continue so let's create a new Branch so I say Main and I'm on May so I can create a new Branch from this main so create a new Branch or say your name is V2 and press enter no I have V1 V2 anime you can see that I have V2 in V2 I have all of my changes which are coming from Main and if I click this publish branch my V2 must be on my repository let's refresh okay so far so good you can see I have V1 V2 and that's it we work on different versions and then when we want to merging our changes we can simply create a new pull request and that's it so I created V2 let's work on this again and this is my project so I open my project again let's open [Music] okay now you can see that here I have main V1 and V2 and the reason of switching to vs code is because seeing the result in vs code is much more easier but you can use any uh tools or any options you want so I want V2 here I just want to create a simple uh refactor let me show you what is my plan let's close all documents inside of my ASP United users you can see I have a let me show you the design I have some Fields you can add your custom Fields into user uh this user and these rolls let me show you the rules you can add any field you want to this role and these users I want to show you that how cool it is so let me show you inside the program that CS here when you are adding the identity you say that you are using this identity user and identity zero you can Define your identity user as your custom user and also your custom role I just want to show you a simple example so I create my users my custom users and use it so let me show you that let's create a new folder inside of my core because I want to create a database entity so I create and GT's folder inside of core and I create a new class add class of this time I say application user that's it this application user has the obligation of inheriting from identity user it must inherit from and user using microsoft.acnet code.identity that's good here you can add anything you want for example I simply use a prop of let's say a stinger for example let's say first name let's copy paste and also I want to use last name that's it and I think this is good so this is my application user so now I want to change my configuration so I simply come here and I say that Siri says that here that at ID I say you must use an application user let's application user okay it isn't recognized let's press Ctrl Dot uh no let's check what is the problem so oh this is the problem I have a typography error so let's rename I say this is app application user yes okay this is application user so let's say app application application user Ctrl Dot it is not recognized again so publish yes it's public let's copy this name from here paste okay oh this is the problem app control dot no it is recognized using jw.sp.core.entities no I say that you need to use application user everywhere so let's check everywhere ID options okay okay we don't need any change here that's good and this is the configuration inside of this identity the next thing is let's go to our dto so for register this time we need to receive using a first name last name let's copy this and after this pass or it's better to be here and also here so I say first name first name in order to be sure that I don't have any error I can use this name here copy them okay first name first name and the next thing is last name last name last name that's so better so no I have another first name and the last name inside of my registered video that's good let's close this and this and let's go to our controller art controller here you can see that this is generic and this is the beauty of using generics I can simply refactor it for now it is receiving a user manager of identity user but which change does that and we said that no you are receiving an application user here so we need to change it also here so we say application you're receiving application user of uh okay I think the problem is let's go to the core to the entities let's rename back to application okay let's check what is using my account is yes 2p this is application this is right exactly so inside the program.cs this must be application user that's right and in art controller it must be application user app is a manager and here you receive application user instead of identity user and that's it and the next thing is we just need to receive that inside of this because we are receiving inside this registered dto we need to initialize it inside of my user so instead of new user I simply say that your uh okay we need to change this identity user to application user oops and this is also an application user no it is right and now I have access to first name is registered to that first name and last name is register that last name that's it let's test this I think that's so good let's register a new user so a string steering a string is thing let's say Muhammad last name username is Muhammad images.com and password is this let's execute it says that we have a problem cannot create a DB set for application user because this type is not including the model and this is the part that we need to check inside of application DB context let me show you here when you are changing let me show you here when you are changing your default T user anterior you need to inject it here also so I say that this identification context no is generic and it's using application sorry application user instead of identity user that's it no it must works let's go to application user and now let's test let's just stick with this test that's so good okay now it says that we have some errors invalid column name of first name well column name of last name no it says that I don't have this column inside of my SQL client they this is data SQL client SQL exception error it means that inside of our database let me show you is a design you don't have the fields yet so what you need to do it is really so simple and it is really so good to see these errors here so when you FaceTime you can simply handle them so let's say CLS add another migration and we say update user entity let's press enter to add these fields okay you can see at column now first name at column of last name and that's good let's update my database foreign close my database and open it again to refresh so open JWT alt tables and asp.net users design now you can see I have first name and last name that's so good now let's check it to see if we have any another error or not and that's all so let's register with this default execute user created successfully Let's test on my database okay it is this one you can see a string is the email string username S3 and anything else and also a first name last name let's test again this time I say mama okay Mt 2023 is my username email is this at sign execute user Creator let's refresh okay you can see I have this user with mt 2023 uh uh username first name is Mama last name is Tahiri and also you can simply return them let me show you in our claims so let's go to controller uh where we have the claims it's inside our logins of course so it is here you can simply add the claims into your token if you want let me show you it is really so easy we also can add another claim any claim as is it is in fact it's maybe seems so complicated but it's simply a key and value like a Json so for this key you can see it is for example this evaluates this keys this value is this it is key this is value so we can say first name uh the first name is user that first name let's copy paste and for the next thing is last name and last name so we added two simple claims first name and users first name last name I use the last name do you see how cool it is so let's test and let's uh register Nua oh let's login username is I think it was Mt 2023 that's it and check okay empty 2023 okay and also for password execute okay I received this token so let's go to the jwt.io and test and decode my token no you can see that I have this name which is Mt 2023 it's my username the next thing is my password JWT ID also I have first name of my mad and last name of Tahiri and that and a lot of them and that's so good so you can see that this refactor is working correctly and I was working on my version two so now I want to persist these configurations and this code inside of my GitHub let me show you how I can do this so let's go here and I have a lot of configurations so let's stage all of them using this plus okay all of them are mistakes so refactor entire API to use application app application user and that's it so let's commit and push that's good it is on V2 let's go to GitHub and refresh okay now you can see that it says it had recently less than a minute ago so inside of this V2 it says that the Spanish is one commit ahead of me let's compare and pull request on V2 so from V2 to main it is say that it's able to mail so this is my uh message refactor entire API to use application user create a pull request okay checking for Ability it says that we don't have any conflict or have any errors so I merge them that's good and that's so good so let's go to here now you can see that I have anything inside of my main branch it says that mesh will request of two from V2 let's check comments you can see that all of my comments are accessed with here for example refactor entire API and that's you can see that this is the refactoring I have done I have changed a lot of things here and here that's so good and also let me show you that inside of vivon we have the exact state of that moment for example inside of controller let me show you we still have identity user but in V2 controller or controller we have application user and this estate will be a state forever until we delete this balance that's so good and this was the refactor for our second part and also we can have another refactors on the next part so let me show you how we can do this for this part it is really not necessary and you can skip this but I want to show you how you can use services and using dependency injection which is really a better idea and let me show you here you must you can see that I have all of my business logic inside of my controller but in a real world project and an Enterprise project it is not a good idea and you always must use services and inject them into your controllers for this we need to use dependency injections I don't want to speak about it because it is really a long topic and we just want to focus on how we can create new service and inject them inside of our controllers so let's do this but before starting because this is another refactor I want to show you how you can create another version so you can see that for now we have main V1 V2 so let's save everything close this and go to here this is my web API so here you can see that I have V1 V2 I want to create a new uh Branch from me so let's go to the main now let's check that if it is update or not so for example let's check on our controllers no it is not update you can see it is already using identity user so simply use this synchronize it would be updated and no if I open a new terminal and I say that gitlog that has one line you can see I have merge pull request of two from V2 and everything of these three factor is implemented inside of me now I want to create a new Branch for with version three so let's click on this Main and create a new Branch also let me show you that you can use create Branch from and for example please provide the name a new Branch name is for example RR it says that from what Branch you want to create but when you are in this main it will automatically create it from this man so I say create a new Branch I say V3 but let me show you the others option you can click on me and create a new Branch from you say your branch name is V3 and select a ref to create the VC Branch from I can simply choose Main and V3 will be created from me we can check instead of out controller you can see I have access to application user so now I have V3 V3 V1 V2 and me that's so good no let's open y project again inside of visual studio and closing and opening it to show you that it is really so simple and it will be updated so let's close everything now V3 is selected automatically in this git in this repository git so let me show you we have main V1 V2 and V3 that's so good so inside of this victory let me show you this is our structure and this is our art controller fit just we don't want to add anything else we just need to refactoring so let's create some new folders here let me show you inside of core let's add a new folder with name of uh interfaces and also let's add new folder of services so we need to create a new interface and because I want to use a new dto I will create this detail first you can see I have login register and update for now I add a new class its name would be art service response dto because I want to change a lot of data in inside of my program between a hot service and art controller it is better to have a standard dto so I use art service response dto that's it here I simply create a new prop I want to use a Boolean uh is succeed that's it I want a Boolean and a message so I create a string off message and that's it so we can simply send a Boolean of a Saturday streaming message inside of everywhere Viva this is my video now let's go here and create a new interface add plus here I choose interface and I say this is I uh series I know that may so you may have some questions why you use interface and service but this is far beyond of this tutorial just stick with me and you can see that how cool it is and on the feature videos we will cover everything you want just let me know in comments so I create an interface of I art service that's it here I want to have some functions so the first thing is I want to have a task and this task will return out service response dto and the name would be seed rolls AC so I I'm going to have this type of task somewhere the next thing is let's copy this line because it is exactly like this we want I want to have a task of odd service response dto of async and for the inputs let me show you that it is exactly coming from out control layer so I'm trying to implement these seed rules and another Series so I created an interface for this series AC and for the register let's copy this registered dtor dto this is exactly the same for register async that's it also I want to have a task of service response dto of login async and for this login I'm going to receive this login detail plugin dto and copy from the exact method to show you that I'm exactly trying to implement that method and this is login AC the next thing is I want again to have a task of uh art series response dto the next thing is make admin acinch and res what I will be received inside this make admin I'm going to receive this from this controller I copy this so I'm going to receive an update permission detail of update permission dto let's copy paste and for the last one is make owner async and it is receiving update permission d2r update permission and dto so this is the interface we are going to use and its name is I art service and we need to implement this this interface and you saw that for example like this I configuration we need to implement the the service and then use that service here but we use the interface here I will show you that so let's create a new service add new class the name is art in fact let me copy from here to show you that it is a better idea to copy from here so add a new class the name would be odd service and this would be a class okay so now we say that this class needs to inherit from IR service so it will be implemented all of these functions and when we use these functions in fact we are using this art service so let's press Ctrl Dot and press Implement interface okay now you can see that all of our interfaces are implemented that's so good and we need to Implement all of them so let's start the first thing is it seems that we have login async but let's start with Seed Road because it is easier let's close this IR service and let's see what we have here let's minimize these okay the first thing is seed rolls here in fact I can copy all of these and then work with it so let's copy all of them uh instead of seeds roll async first let's change this to async method and then let's paste all of them so we need role manager and also on the feature we need to use user manager so let's and also we need to add configuration so I copy all of them from here and I paste them inside of our service before all of them not here inside of my service I paste all of them okay then I need to inject them again you saw that here we have injection of them inside of my odd concealer which was Constructor let's inject all of them so Ctrl Dot and we say that generate Constructor with this that's so good let's move these two lines to the up let's press Ctrl dot again to create role manager add parameters that's good and also let's control that and add parameters now you can see that this is exactly the same structure we had here and we had exactly the same structure here now we have all of them here now we can use everything we want now I have access to all of my configurations my role manager and user manager now let's implement seed rules this is exactly the same and I say if is Honorable exists and is admin role exists and its user.exist return this time we cannot return okay because we are going to return an odd service response so let's say that I cut this message I simply refactor this I say that return and new art service response dto uh it sucks is they say it is true it's no problem and we see your message is role seating is already done else you can work all of them and let's copy this here for the return we can use this message and delete the previous line so simply we say return a new art service response detail of is succeed is true and the message is roll siding done successfully so this was the first one seat rules async we can then refactor our control layer now we refactored everything and from here we simply return a new auth response service that's all this was for seed rolls after seed rolls we had to use login and register so let's go to the login and for now I just comment the scissors next thing is this register let's copy all of them from here okay copy and comment there that's good so for the login I'm receiving the login detail again here it says that you have a weight okay I'm going to use async so we say that varov is X is the user equals to this uh I'm sorry it seems that we have some problem login register no no no no no no no no no this is login we need to this is the right function register async so let's paste them here and that's it so this must be I think of course and we say that is exist user is a rate of user manager that's fine by name oh okay that's so good if his user exists return in fact all of the business logic is equal we just need to change the return so let's copy one of or let's create it we can simply say let's cut this and here we return A New Path service response dto is success is false and the message is username already exists that's so good so we just refactored this return then we say new user okay okay no problem that everything is good here again we need to use a return so let's copy this return from here and this new we return a new author response so it success is false and let's copy this string from here and delete this okay so uh so sorry no it wasn't this it was here so uh what happened no okay here let's do this correctly we written a new art response what was the name odd service response or service response R series response detail is success is false and the message is error string that's it and if we have any error we simply return this file it success is false and the message is error stream and after this if we have this actual async that's okay and also we have user created successfully so we can change this so let's cut this and simply return a new oops a new auth service response dto and this time you say your succeed is true and your message is user created successfully and this Ctrl s so I think this is a working let's minimize this register the next thing is login so this is register and then let's work on login and let's copy everything [Music] copy and comment there so for login let's paste everything the first thing is of course we need to have publish async then we can say that user is if you're okay if user is not return let's change new art service response dto of it's like cities of course files and the message is invalid credentials that's good and also the check is password and if it was correct exactly this must return so if not is password let's save and we return this exercise file and invalid credentials and that's all good the next thing is this user rolls and everything is okay or token is generated or can we need use just generate token let's cut all of this because we don't need it inside of the controller anymore let's cut and paste it on the last okay uh and so no generating what Json web token is okay and for the return we just need to return this token that's good so let's return a new art service response detail okay and this sucks it is true and the message is this token this time we are returning this type and that's it go to S so this was for the login let's save up so this is login and what do we have anymore okay so as it rolls good register okay login okay the next thing is make admin and make owner so let's copy this make admin from here comment it inside of controller uh make admin so minimize login async and minimize good so make add me paste and let's make this to an async function so a lot of user is a way to understand by name and if user is null we can simply return a new part so this is one dto is successive false and the message is invalid username that's it else we change the rule to add mean and we simply return I don't want to use automatic response okay we return a new art Services first detail of is success is true and the message is you say it's not an admin that's so good and the semicolon this is the make admin and the last one of course is this make owner so let's copy everything and command no inside of make own air let's paste it so publish async task of make owner okay user is this if user is not let's copy from make admin because it's exactly the same we return it sucks is false and messages email username else we return on the Lima you see that the owner in fact let's copy from here it is exactly the same and instead of this returning okay we return a new which is slices through our user is now and owner so we refactored everything and know all of our return type is or service response dto let's minimize everything that's so good you can see that I have login async make admin AC make owner is async register AC C roles async and generate new web token which is private and I don't have access to it I just have access to this file and now it's time to go and refactor everything here so I don't need like all of this anymore and also I don't need this Constructor anymore so I delete them and I simply want to use interface of this odd service I mean this iot service so let's create a private read only of I ad service of Angela ad service and let's create a Constructor and receive it and we say that underline our service is odd service now let's change everything and instead of the seed rolls let's first delete everything and now I have these citrols inside of my service so I can simply call it I'm using a new variable of our seat rules is a weight of Mandela or service dot I can simply call my service which is seed rolls async that's it and because in both let me show you here in this seed I simply return this is succeed and a message so I can simply return an OK read my seed rolls that's it the next thing is I want to change my register so let's delete everything and here I don't need all of them I don't need them anymore okay that's good so I say that of register result equals to a weight of underline a service start register async and what is the input of this register I think let me show you it receives a registered dto which is exactly our registered to you and that's it so after this I don't want to take care about the operation inside of this I simply say that if my register result that is Success it means that it was successful okay this is a problem it must not be like this okay so if register result that it sucks is simply you can return an okay with all of your register result that's it and if it is not sexy it will not return here and it comes to the next line and we simply say return a bad request feed register result that's so it let's register uh later and we test it later for now let's complete our refactoring and login I delete everything I don't need them now because they will be implemented it is implemented inside of my service and here I simply say that that of login result equals to avator what is it yes it is Art service Dot Login async Oops why this is working like this that login I think with the input of login detail and exactly like that type of the register we simply check the east side we say that if login result that is Success everything is good and you can simply return a new okay with login result else if there is success is not true it means that something is wrong so we can simply return a unauthorized with my login result that's it it is really much simpler and much more readable isn't it so the next thing is make admin so let's go to the make admin and delete everything from here and we say that that operation result equals to Evita and service what method we need to use of course you need to make admin async and its input is an update permission detail then we check if the operation result that is succeed you can simply return okay else you can simply return a bad request with operation result that's it let's do the final refactor and for this let's copy all of them from here because it's really like it so we say that of operation result is a rate of our service that's make owner async with update permission dto and if operation result is Success return okay with operational result which is this and else returning path request so I think all of our refactor is done and in fact let's save everything and let's start and before that I will go and okay this is starting I will go to database okay this is my users I go to the edit and I delete all of them delete yes touch is deleted uh for user roles exactly I delete them because I want to test everything after my refactor delete the better way is to have tdd approach but in this video I I'm trying to keep everything simple so I don't use 3D approach so select 1000 rows is empty users is empty and everything is good so let's test and let's set our rows to see if everything is working or not or do we have error of course we have error and I just wanted to show you that if you see this error you know what is this it says that systems that invalid operation exception unable to resolve series for type of interface.irth service it says that I cannot have access to the implementation of IELTS service although let me show you here although we implemented this IR service using art service but it has not accessed in fact it's too simple we just need to let me show you here inside the program.cs you need to use dependency injecting so after this add DB add identity and configure identity and add authentication and jwtp area and before these Pipelines this is the part I want to use inject my dependencies oh let's say inject app dependencies which is called as dependency injection okay so here we can simply use Builder Dot Services dot we have three famous part of injecting the first one is transient the next one is scope the last one is Singleton and we can speak about them a lot there are all the different features and I don't want to speak about them here I just simply use a scope the syntax is something like this Builder that says that at a scope and here for the scope we are watching for iot service and we say that IR service needs to be injected using art service so using this line we say to our program that's yes that when you receive an ielt service in your Constructor inject add service into it that's so easy let's start again and check to see do we have any errors or not and let's test seed roles execute okay now you can see that I have 200 it says that the response body in fact is interesting it says that I have its success is true and the message is roll CD done successfully let's test roles okay let's check it again this time it says that it succeeded through but the message says rolls seating is already done and that's so good isn't it so it is working let's register I say try okay user one or let's say if name last name let's say l name username is user one email is user1 at user1 okay no problem password is user one let's change everything to user one because I want to just a quick test execute is a user created successfully that's so good let's check okay you say one is a one first name last name it seems that everything is working correctly and let's login using my user1 and user1 execute execute is succeed through and now you can see that I have another extraction and it is also good so I'm receiving inside of my body receiving an object it has its success of true and the message is my token that's so good and let's test make admin so let's write out user1 execute is Success Through may say user is no and admin that's so good let's check make owner user one message is user is no and owner let's check user roles okay my let me show you that inside of user roles okay you can see that this user has three groups that's so good and let's test uh let's login with this username and get a token okay this is my token now I have access to everything and I test I say that for the first one okay for this one I use a beer token this is my token send okay 200 for the get admin roles let's delete everything and paste my token and test 200 okay and for the last one let's paste and okay you see you can see that all of my refactoring is working correctly and it seems that everything is working fine so this is the final step of our project so let's add all of them to GitHub and create another pull request so I have five files that are changed and I stage all of them refactor to use I uh service and art service so good uh commit stays then push in V3 okay is it push it yes pushing you started uh okay it seems that it pushed already that so would let's go to the here and let's go to YouTube uh it says Victory had recent change so let's go to V3 it says that we have three comments let me show you beautiful thing in V1 or version one we have six comments okay in V2 we have eight comments in V3 we have 10 commits and also in main what do we have we have nine commits because we are we just committed from V2 and we don't updated it yet so let's create a pull request from V3 to have all of our recent codes inside of my main so refactor to use okay good create pull request checking for every smash good merge I confirm my merging watch now let's go to my YouTube repository of JW 2006 and you can say I have me inside the main I have 11 comments inside of V3 I have six commits in V2 I have eight comments in V3 I have 10 commits and that's it so if you have any questions and any further questions about these topics and these branches just ask me in comments and we can speak together and I think for this project it is done and let me check if you have anything else no it's okay just let's close this and I'll show you how you can use this repository so inside up Drive F we created this okay no let me archive okay let me cut that folder so if I want to use this repositor I can simply come here and close use this copy and go to here and I say a new curve so I simply say it get on this address okay wait okay let's go so now if you open this with your vs code or anything you want let me show you like let me show you for example project there is really no difference between IDs I trust this project okay there is really no difference what is your IDE or code editor the standard is the same for example inside of this idea products you have access to all of them for example here is you can set my git branch is main let me show you I have main origin name origin V1 origin V1 origin V3 for example for this may I have let me show you inside of my controller this is my main it is the final product of course this is it so let me go to the V1 checkout you can see inside this controller I have this three and I have user manager read identity user the first version that's cool isn't it let's go to version two check out this time I have application user and I'm using first name last name Insider version two and for version 3 check out you can see that I I'm using iot service and I'm using the register result and all of them and this is the beauty of using the GitHub and also on the main if I check out the main the main is my final result so this was all of what I wanted to cover in this video first and we created the basic implementation of our JWT refresh tokens then we refactored it to use application users and we added our custom fields to our users then we refactor and we used our service and you saw that it is really a better idea to use your services and use interfaces for them and this is all of it so let me know if there is any opinion or any comments thank you for watching this long video I know it was long but it is really vital and this is really required to knowing all of this and like this video please and comment for me for anything you want and subscribe to my channel have a good time and goodbye
Info
Channel: Dev Empower
Views: 8,881
Rating: undefined out of 5
Keywords: .net 7 web api, asp net core web api, asp.net 7 api, asp.net api tutorial, asp.net core api, asp.net core api crud, asp.net core api entity framework, asp.net core web api, aspnet core web api, dotnet core web api, dotnet core web api tutorial, entity framework, rest api asp.net core, asp.net, .net core, web api, asp.net core, .net core web api, jwt, authorization, authentication, role-based authorization, .net web api, asp.net web api, security, .net, c#, jwt authentication
Id: KRVjIgr-WOU
Channel Id: undefined
Length: 157min 48sec (9468 seconds)
Published: Sun Apr 02 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.