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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello friends thank you for watching this video i am muhammad and today we are going to be exploring how we can add shade ability token into our application we are going to basically add uh token-based authentication we're gonna create the register mechanism we're gonna basically create the login mechanism as well as well we're gonna be adding some authentication to our controllers so not anyone will be able to call our controllers so the user would need to first register then they need to have their tokens and then they need to send their tokens into the action itself so it will be able to authenticate them and basically basically get the result that they want so this is going to be very exciting video so please grab your coffee and let's get started we're gonna start by mapping first the authentication approach that we're gonna be building we're gonna go through the flow of our authentication from sending the username and password what the api will do and what the api can respond back so let's get started so first of all we're going to be utilizing similar to last time last time which is going to be the swimlane journey and basically we're going to start mapping the request from the front end all the way to the api and then all the way back so in essence what we need to do here is in the front end the user will have to start their journey which is this nice green circle so let's make it green and basically once the users start their journey what they're going to be doing is they're going to be actually filling their username and a password so here they're going to input let's say email password and let's make this a bit smaller okay so once they input their email and a password the next step is basically what we need to do is we need to send this request to the backend and basically here we're going to say this is the back end oh yeah at the back end and basically we don't need this oops not need this we don't need this so the first thing or the first request that the back end is gonna do is basically validate the format of the request that's the first thing so basically once we send that request to the back end the back end is going to receive it say thank you thank you very much for sending it to me now it needs to validate it so basically it's going to check if the email is in the right format uh it contained for example at something it has the right basically the right email format and once it's validated the first step we're just gonna be doing is it's gonna check if that email exists so what we can do is let's add this one here as well and we can say this one from the database so we can say here and let's remove this for now we can just take this one let's see you can copy this and we can put this here and we can say check if email exists that's going to be the first step and basically how does the check if the data if the email exists or not so in essence it has to go to the database so let's get this decision and here it's gonna look up the email so basically the back end it's gonna send the request to the database telling it listen to me do you have uh this email available and the database is gonna respond so let's make this a bit bigger so we can see what's gonna happen see okay and if we move this a bit here i think yeah so once we have asked the database to check the database can i return to think so the first thing that's going to be returning to us is let's make this folder email doesn't exist as simple as that so that's the first option that the day that the database can return to us so if the email doesn't exist which means that we have to return that to the user we're going to return an answer as invalid credentials we need we should not tell them exactly what went wrong we need to make it as generic as possible so we use invariant credentials and once we invert the credentials we're gonna basically end the journey there so we'll make this as red and we'll end the journey the journey has finished so that's the first approach so in essence what we did is we inputted the email and password it went to the back end it validated the request then the first check that it did need to check if the email exists then the back and send the request to the database to check the database told us here the email doesn't exist we return the message to the front and say and find the credential and we stop so the second one is the email actually does exist so that's the next second step the email actually exists which is really good for us because we can now continue in the journey so now that the email actually exists the next step that we're going to be doing is we need to validate if that email and password combinations are enough for us to actually grant that user access so let's see what's going to happen here so let's try to make this a bit more big so we can actually continue working with it inside okay so the next step for us i'm just looking to make sure that everything is still in frame so let's put this here so once the email exists the next step is we need to validate the password the email password combination so that's the next step so how do we validate that it's gonna be also through the database let's make this a bit bigger let's put this here and then we're gonna send another request to the database to check if our validation is valid we're going to say validate combination and again the emails the database is gonna return to us two types of answers so the first one it's gonna be invalid combination and basically if we have an invalid combination we're gonna return the same thing again to the users and basically once we return this to the users we'll be able to actually tell them that there's an invalid credentials we should not tell them that there is a mismatch between the username and password because we should not uh give specific details it's all for security purposes so we need to try to make it as broad as possible so that's why we specify invalid credentials so once we have done that the next step for us is we're gonna see what is the happy path so in case there is a valid uh combination so from here the request is gonna come and let's make this a bit bigger okay so now we have a valid credentials once we have a valid credentials the next step for us is we need to actually create a token for the user because basically what we need to do is we need to return to the user that token that they're going to be actually utilizing in order for them to do any subsequent requests so in case they want to for example view their account get any types of information they need to attach that token to the header of the request so once we have this valid credentials the next step is to create a token based on the credentials and once they have created a token based on that credentials what we need to do is we need to basically return to the user we can return here access granted and basically once we return access granted what we need to do is we need to end the first journey which is the login journey and this we need to be green because basically the journey has completed successfully so in essence this is the flow that we want to start to build for example for today we're going to first start within the front end which is going to be either swagger or any types of api communication application and basically like insomnia or postman so it doesn't really matter the front end so what we're going to be doing is we're going to input a username an email and a password we're going to send it to the end the back end is gonna varied that this is an email and then once it's validated oh let's add another condition here so what we can do is let's make it like this see it's always better to go and refine your journey because you you're gonna be needing a couple of iterations before you make sure that it's the final one so let's take this one here let's paste this here and basically oops let's connect this one to this one and let's connect this one here so that's the happy path so the email actually exists and we are able to actually uh validate it so if in case it wasn't validated so let's put this connected to this one so we'll have more space okay i'm not sure why it's being directly linked to the line let's try to zoom in a bit okay now we can see that we have different options okay okay let's make this a bit lower okay sounds good so now what we can do because this is in case it's a valid credential so we're going to say valid and in case if it's an invalid credentials we need to stop so we'll put this here we'll move this a bit forward and basically here what we need to do in case it's an invalid credentials we just need to stop the request and basically from here we're gonna stop the journey and we're gonna see here invite the credentials invalid basically let's update this so first of all we're going to check if it's a valid email or not so if it's a valid will continue if it's invalid we'll send invalid credentials and we'll stop if it's valid we're going to check the email so here we say email doesn't exist we're going to say false because it doesn't exist and here i'm going to say true because it exists so in case it doesn't we return again invalid hidanger and stop in case we continue to exist email functionality to check uh now we're gonna have to validate the email and the password combination once we validate that combination that inside the database if it's a valid combination which is gonna be true this whole story it's an invalid combination we're going to return invalid credentials and we're going to stop if it's a valid combination we're going to return true and basically once it's a variety credentials we're going to create the token then we're going to return it back to the user so that's going to be the stops perfect so now what we're going to be doing is we're going to go through our terminal we're going to be basically creating the application and then we're going to be actually starting adding everything inside our application so we can have this flow implemented so let's get started so the first thing that we're going to be doing is we need to go to github which is my github account so github mohamed let's go to my github account if you're not following me there please uh follow me that will be really good i got a new achievement that's good i didn't know that i had this achievement so okay let's zoom in a bit so if you're not following me again on github please follow me so what we're going to be doing is we're going to go to the repositories and basically we're going to utilizing the cloud repository which we have built in the last video so if you don't know how did we do it how do we how did we build it i'm going to be linking the video here somewhere where you can actually click on and see how the full process of how did we do and build the crud and hopefully that will be able to help you so once you do once you find this netsix dash cloud just click on it and we need to go to the master branch and once we come to here we're gonna just come to code and we're gonna copy this one so now we have to go to our terminal and inside our terminal let's navigate to where we want to have the application i'm gonna have it inside my working progress folder i'm gonna create a new folder i'm going to call it authentication i'm going to go to this folder and basically i'm going to clone the application here so get the clone perfect and now the application is cloned uh what i can do is i can just open it so i'm gonna be utilizing there's multiple ides you can utilize here so for example you can have visual studio code and basically visual studio code is a free tool which you can actually utilize to utilize the visual download which is a really good tool you can have visual studio format because i'm on the mac which is also a very powerful tool i think it's still in a preview so it's not this one that's the wrong link it's gonna be this one yes so that's also a very good tool you can actually download and basically you can start using for free on the mac and basically the one that i am currently going to be using is rider so basically let's open it up and in essence ride is a very strong ide specifically for not on a mac it has a lot of great potentials has full support for that net six and it's a very fast id so it is a paid one but you can get it for like 30 days for free but again you don't really have to utilize writer you can either use visual studio or you can use visual studio code and basically you can take it from there because i already have a license that's why i'm going to be utilizing it so now let's open the rider so now that i have ryder open i'm just going to click on open here i'm going to go to my desktop work in progress authentication crud.net 6 and i can see the application that i have checked out i'm going to click on the formula one app assalaam and i'm going to click open yes open and trust let's put this here and basically right now we can see that my application is loading and basically i can see everything that we have built before again if you did not see that video i highly recommend going through it because we go into details how we can create this how we can connect it to a database uh how did we build the team's controller so on so forth how we migrated it from an in-memory database to an actually fully fledged database so once you have done all of that uh the next step for us is we're gonna start actually first by building and adding some new get packages and once we add these new get packages we're gonna start actually building our authentication mechanism so the first thing as we said uh is we need to add some packages so we have multiple ways of adding packages so if you're utilizing rider you can just right click on this on the application name you can click on manage new get package and once you get to the nuget package you can input the package name that you want to install so for example the first one it's going to be the microsoft dot asp not core dot authentication dot j wt better this one the first one so once we choose which nuget package we want we can just click on it and click on the plus button and we can click on install and you can see it has been installed successfully so that's one way of doing it the next step is let's look through the terminal because if you're utilizing visual studio code you can actually do it directly through the terminal so let's navigate to the application here and we can see i'm inside the application even if i do not build it will build perfect so the next way we can actually add another nuget package is by utilizing the command line and basically we're gonna put dot nut add package microsoft dot asp not core dot identity dot entity framework core and let's see now we can see it's being installed and you can see it has installed successfully so if i want to double check all of the new get package that i have i can just right click on this i can click on edit and then we can see here at the cs file and i can see here the two libraries that i have installed which is great we still have one that i want to add which is basically let's do that through the command line as well so it's going to be not add package microsoft dot a sp nut core dot identity dot ui and that should be it okay great now i have installed all of these and if i come here i can see that all of these has been installed uh the next step is basically i need to update my app settings.json in order for me to have the secret key and you might think to yourself okay what is the secret key and why do i need it and for that let's go back to our web browser so in essence let's go to one of the best browsers to j4jwtt with jwt.io so we already have covered this previously but if you are new to this let us understand what's happening here so basically this is a json web token an adjacent web token is basically formed as a string basically in essence and it's compromised of three different sections so the first part is going to be the header which contain that algorithm type and basically it says that it's going to be and jwt token string the second one is the payload which is the data that we are passing additionally inside the header inside the request story and lastly it's going to be the signature and the way this is built is basically all of these are encrypted values so although here we can see that i have a name which is a generic one and i have some kind of a random id which is generated but in essence all the payload information that i'm passing which contain the keys in order for the for the server to decrypt and validate that this is a valid token that the system has generated and it's not any random jwt one can have some kind of authentication as we can see here and this authentication in essence is being utilized in order for us to validate the authenticity of the jwt token that we are the in fact the system which generated it it wasn't any other random system we need to validate that the value inside of it are actually encrypted in the right way and we are able to decrypt them so on so forth so that's why we need to have an encryption key inside an order for us whenever we generate this token and we send it to the user and once the user sends send it back we need to be able to decrypt that token and then basically see the information and validate it so that's why we need the key so now let's go back to ryder and what we're going to be doing is we're going to go to app settings and inside the app settings here we're going to add a new section and this section we're going to call it jwt config as simple as that and then what we're going to be doing here is we're going to basically this is going to be the secret that we're going to be utilizing in order for us to uh encrypt and decrypt the jwt token key that we have so we once we can once we have it here what we need to do is we need to have a random string which is generated we can put for example my name but this is not really good as a secret the secret needs to be long and complicated so if we go back to our web browser and we can just go to google and we can say here let's zoom in a bit generate random string online anything okay let's see this one random string generator uh only necessary and basically i want it to be 25 characters let me zoom in and basically it should okay each string should be 10 characters long okay let's make this 25 here i only want one and numeric uppercase and lowercase yes why not i think that should be it and if i click on get strings oh what did i do wrong okay let's put 20 then and this is a sample string that has been generated for me so let's let me copy this go back to rider put that random string here and i click again i got another one so let's copy them and let's use them both as a secret so for example here this could be my secret that i'm using to encrypt and decrypt my tokens and this is a like for development purposes it's fine for us to put the secret inside the app settings but once that application is being put on any like qa environment uat environment broad environment that should not be here or basically that should not be committed into our get repository whatsoever what we need to do is we need to put it somewhere seek safe which is could be like a application key vault on azure which basically that will allow us to communicate with the keyboard to get those keys so we should never ever put uh the keys directly into our git repo or on our application because basically it is not well it makes our application very vulnerable so that's why we should not put them there uh but for development purposes and for to make this video a bit simpler and not like six hours long we're gonna utilize it directly now from the app settings so once we have done that the next step that we need to do is uh inside our models what i'm going to be doing is i'm going to create a new actually outside the models here i'm going to create a new directory which is a new folder and i'm just gonna call it config configurations and basically inside this configurations folder here i'm gonna add a new class and this class i'm gonna call it jwt config and basically add and basically this class here that i have is basically the same thing as this class so in order for me to directly connect from the app settings and be able to put this information out in my application i'm just giving it the same name and as you guessed it we're going to have a string here which is named secret simple as that so once i have done that and basically i have created this the next step for me is basically injecting this inside my program.cs so let's go to our program.cs and now what i'm going to be doing is basically utilizing this the builder configuration in order for me to get my keys there so we're gonna add this after we do the db connection so let's do it here and basically we're gonna put builder dot services and we're gonna say that actually yeah services dot configure and here we're gonna configure our jwt config and basically we're gonna direct it to find it inside our configuration so we're gonna put basically builder dot configuration dot get section and then here we're gonna specify the same section which is gonna be jw t config so that will make it easy for us because basically what we're doing is we are configuring the service so whenever we want to inject a jwt config it's going to check here our app settings to find this function between wtconfig is going to fill the secret inside that class and basically will be able to access this directly so once we have done that the next step for us is we're gonna actually now start building our jwt authentication service so let's start with this okay just an extra point before we move on to creating our jwt service this section here will allow us to utilize our configuration within the di container and basically that's within our dependency injection container i just wanted to mention this one here because you might think yourself why are we doing it like this it just will help us within the di container so now that we have discussed this now let's start building our jwt service the first thing is we're going to utilizing the builder we're going to connect to the services and then we're going to say we want to add authentication and you can see here because we have added all of those nuget packages all of this will come up all of this will be available for us directly so add authentication and basically we're gonna provide options and we're gonna be building the authentication options and here we're gonna do this and then we're gonna close this perfect so now we are added the authentication basically what we're doing is we are updating our middleware in order for the middleware to understand there's going to be authentication so that way whenever a request comes in with a header which is contain authentication it will know that this is a secure request and it needs to go through the authentication process in order for it to validate the token which is coming in which is really important for us to do so the first thing we're going to be doing is we're going to put options dot we're going to say default authentication scheme and it's going to be jwd bearer defaults dot authentication scheme so basically here what we're gonna we're saying is the default authentication mechanism that we're utilizing within our application right now is the jwt barrier default scheme and we can see here that it says bearer on it so when we now when we are building the header we can see in the header we're sending the authorization of the i have a key and the value is going to be better on the token and we're going to see this in more detail but it's very important for us to put this from now the next step is we're going to put options i can write options the default scheme and it's going to be basically the same thing jwt better defaults dot authentication scheme same thing second we're gonna put options dot default challenges scheme equal jwt barrier defaults dot authentication scheme so all of these schemes so for example if we hover on this and we can see it's used for the async authentication challenge so whenever we want to challenge that scheme so for example want to validate it we need to utilize we're going to we're telling it that it needs to be challenged challenging it through the jwt barrier the default authentication is basically the fallback so in case the main one did not work it's going to be falling back on this it's also it's all part of building our authentication mechanism so once we have done that the next step for us is let's make this a bit smaller so we have a bit more space uh what we're going to be doing is we're going to add a better configuration so before the semicolon and after this brackets here has been uh has closed we're going to just put a new line and we're going to put dot jwt bearer and basically once we have add that what we're gonna be doing is we're gonna be updating the configuration for it so what we can do is we can just put jwt and basically we're utilizing a lambda function for us to build this uh configuration for the bearer so let's put them all the way here and basically the first thing we're going to be doing is because all of the jwt barrier tokens that we're going to have we're going to be having is gonna be based on the secret key that we have in order for us to actually create them and basically validate them so these two are gonna be working together so what what are we gonna be doing here what we're doing is basically we're telling our application our our middleware that for all of the authentication mechanism that we have for encrypting and decrypting that keys we need to actually know uh we need to get the keys from the app settings in order for us to utilize it so that's what we're doing so we're going to say var key equal encoding dot ascii dot get bytes and basically we're gonna go to builder dot configuration and then basically we need to connect with the jwt config oh sorry i forgot one thing which is gonna be actually let's do it like this yeah configuration dot cut section the key and then dot value and that's it so that's one way we can do it well basically what we're doing is actually let's do it forgot the secret so in essence what we're doing is we are i'll explain this right now but first of here we're connecting to our configuration we're getting the key jwt config with the secret and we have the value here and then once we get the actual string of this we are convert converting it to a array of bytes because that we're going to be utilizing for our encryption and decryption we cannot use it as a string it's better for us to utilize as an array of byte so once they get the strings from the app settings we are converting it to an array of points so once we have done that we just got it here we did not inject it yet so that's going to be next so first of all we're going to say jwt dot safe token it's going to equal to true and basically if we take a look at what safe token does it's basically uh it allows us to store the token inside our header for the authentication properties so that's why we need to actually keep it there so basically it's diff we are saying that once the authentication has been successful we are keeping the header inside that request so we need to keep this the next step is we know we need to start to build our jwt dot token validation parameters and these basically validation parameters which can allow us to verify that the token that we are receiving as a token that we have generated through our application and it's not any random token that someone found on the internet only and using in order for them to access get access to our application so equally new token validation parameters let's build it from here so the first item that we want to validate inside our parameter is we need to basically validate the signing key the issuer signing key and basically what this means this means that we are using uh for every single token that we are receiving we are checking the credentials of the key that is being used for us to sign it or encrypt and decrypt it so that's why it's really important for us to do that so the second one that we need to validate is issuer signing key so the first one we're going to say true as well uh i will sorry the issue with signing key here we are providing the key that needs to match whatever our token is being sent whatever the whatever exists inside our token so the issuer signing key it's gonna be basically new psymetric security key and we're going to pass the key so the first one we are saying that for every talking that we are receiving we need to check the key that exists within it in order for us to make sure that this is a valid key and basically how do we do that we're basically passing the key that we have got from here and we're telling it you're gonna use the key that we currently have and you're gonna compare it to the key that the token is sending and you're going to do the uh you're going to do the encryption and decryption of these keys to make sure that they are equal and basically if they are valid and they are equal we can actually continue with that request if not we need to stop because this is an invalid key so that's why this is really important for us to keep here so once we have done that the next step is we need to validate issuer it's going to be validate when the date issuer and for now i'm just going to put false and why you might think to yourself okay why are you putting it false because it's really if it's really important for development purposes and i'm really emphasizing on that sometimes from the machine local machine it this creates an issue because the https ssl credentials that is being generated when we run the application locally our machines can get invalidated and that conclusion is cause an issue issue but for now we're just gonna make it false but again once you go to plot you need to switch it through or you go to any actual deployment but for now just i'm gonna say here for the the second one is going to be let's add a comma after we validate the issuer we need to validate the audience i'm also going to say false again it's only for development purposes i'm saying false and then we're gonna say require expiration time again false and you might think to yourself why so basically uh jwt tokens are short-lived tokens and basically they only live for 30 seconds and then they die and then basically to get the new ones or basically get invalidated they live for another 30 seconds or no matter how long excuse me or no matter how long we actually uh give them their lifetime or their lifespan they can live for that time and then they are not usable anymore for development purposes uh i'm not gonna be actually generating multiple ones one after another if we are testing in real world scenario uh we're going to mute there is something called a refresh token which is another token that you send with the main token in order for the authentication mechanism be able to switch those token on the fly that's going to be a separate video from this after this video so the first one we're just going to implement normal authentication the second one is we're going to implement refresh tokens how we can actually refresh these tokens within our requests and for the sake of again just simplicity for this video just we can see how we can create these tokens i'm not adding time expiration but again this needs to be happening and for once we go to production so for this one i'm just going to say for dev as well and basically we're gonna say needs to be updated when refresh token is added okay so now that we have covered this and the last one is we're going to say validate lifetime i'm going to say false actually true because we need to make sure that the lifetime of it is value and we can see here what does this mean so if you hover on top of it we can see that the valid data lifetime is basically validating the lifetime of the token that we're sending so let's say the token that we are generating we're telling it that it lives for a minute so it will be able to calculate for how long that token is being uh has been created so if it's less than it will still be a valid token that we can use if it's longer than a minute it will not be valid and it will be rejected so that's why we need it here and all of that so this is basically going to be the main items that we're utilizing in order for us to have that to add jwt token to our authentication and basically defining the authentication mechanism that we want but we are not done yet there's a lot of stuff still that we need to add so the next step is basically we're gonna be actually uncheck if we have already add authorization which is fine but we also what we need to do is we need to do app dot use authentication and basically what this is doing is here we have defined inside our middleware that uh that we're utilizing authentication we're adding authentication to our middleware and we're defining all of these different options and basically here what we're doing is we are actually using the authentication inside the middleware so this two step one is adding it and the other one is basically utilizing it so once we have added the authentication now let us just do a quick uh build to make sure that everything is still running as it should be so let's run the application we can see the application is running and let's open this inside my browser so that's i don't want to use it in safari i want to use it in edge so i just put it here and let's zoom in and now right now let me close this right now i don't have anything extra all i have is my normal application and basically if i click on add teams here sorry get teams i should be able to see all of the team that exist inside my database and currently there is none we should be fine if i click for example post let me try adding a theme i'm gonna give it an id1 i'm gonna give it the name i don't know mercedes amg f1 the country is going to be united kingdom and the team principle is total wolf if i click on execute what did i get i got the 201 which has been added so now if i click on get everything i got my mercedes theme back which is perfect so now our api is working and basically everything that i have added did not affect yet which is great the next step is basically we're going to be actually going back to our source code so let's go back to our application and you might think to yourself okay that's great now i have everything stored in my application the configuration for my authentication but where will i be actually adding my username and password where are all of this information being stored where i can see my credentials where i can see all of the users that i have and currently if we open our database and let's connect to it if i open here my database in my tables i can see that i have only a themes table that belong to me these are defaults one for sql lite and this one for the migrations that we have added last time if you don't really know i really suggest you go watch that video because it will really give you a help on the migrations but right now we can see that i only have one teams i don't have any word which says that username password or all of that data that i need so what can we do because we are utilizing.net there's a lot of features and a lot of stuff that does not provide us which is we really take for granted and one of these main features is basically identity and basically identity is a way that we can actually directly create those tables to manage which is going to contain our credentials username and password roles different access that we can give all of that can be provided for us directly out of the box and identity will take care of this managing those tables so on so forth so how can we add this and how we can utilize it so first of all we have already added the new necessary new get package the second way that we're going to be doing is because we are communicating with the database what we need to do is we need to update our db context and basically right here what we're doing is we are just inheriting the normal db contacts as things that exist with an entity framework so the steps that we need to do in order for us to update this it's going to be very simple so instead of utilizing the normaldb contrast not db contacts we're going to be utilizing the identitydb context and basically the identitydb context that we need to add this we need to add those references and basically in essence the identity db context if we hover on top of it so let's see it's basically a basic class where we can actually have all of the identity information available for us i know that will not give a lot of help but in essence all of the tables that we're going to be needing for the identity it's always like the users tables they're all where we link users with role and all of that the claims all of those will be provided for us for free without us doing any work from the identity framework and this can elevate a lot of the work for us so instead of creating those models here creating those tables doing all of those connections together we are all inheriting them from the identity and basically we will be able to see them in our database by simply just utilizing identitydb contacts instead of utilizing db context so once we have added all of this i basically just updated a single line to be honest a single word what we're going to be doing is similar to what we have done last time is we're going to be opening our terminal and basically we're going to do migrations because basically this is going to be a database change and the way we're going to be reflecting those changes to our database we need to create a new migration and basically update those migrations to the database so let's do this right now so we're going to put dot nut migrations and we're just going to say adding identity data to api and right now okay i forgot to put ef see still early morning and now this should work so basically i'm saying dotnet entity framework migrations and then i'm adding it so now we can see that it has passed successfully and if i open my migration folders i can see here that i have a new uh migration file if i open this migration file i can see that i have a roles table being added i did not add this it's all came from the identity i have asp.net users was being added i have asp.net role claims i have user claims asp.net user claims i have all of this table available for me out of the box i can even have asp.net user logins user tokens all of this information is available for me out of the box without me having to do any single thing and which and here you can see the power of microsoft identity because basically it it took a lot of the heavy lifting that i need to do in order for me to create all of this so basically with any uh migration the first step is actually creating the migration the second step is actually implementing it in the database so we're going to put dot not ef database update we're basically updating the database with those changes and now we can see that uh changes has been implemented successfully so if i click on table and i refresh it i should see all of my tables being added and i can see here that i have asp.net all games being added asp.net roles i can see my users table my users token every single thing is being has been added automatically for me in my database i will i can manage all of my users i did not have to do anything all i did is basically add this identity in front of the db contacts instead of utilizing only db context i can i just used identitydb contacts and all of this has been generated for me which is really cool okay great so once we have done that the next step is basically we're going to be doing is once i send the request to my api i need to receive a response so basically that response it's going to be if in case the authentication is successful i need to get my token i need to get if it's a pass or fail like if the request has been success or not and then i need to get for example if there's any errors or the timestamp of my request any any information that i need so to make it easy for us i'm going to be creating a model inside the our application so inside the models folder we're going to be creating a new actually yeah let's create a new class and we're going to call it uh auth result basically it's the authentication results that we're going to be needing and all i'm doing right now here is just put a string which is going to be of type token and in essence what we're also going to be doing is let's add if this is a so bull boolean we're gonna say result so if it's success or not and should we add a list of errors why not so property let's make it as a list of strings and we're just going to call it errors that should be fine so once we have those the next step is we're going to be actually creating the model that we're going to be receiving so let's do this right now so that's that's the authentication results but what about the dto or the basically the request button that we're going to be able to receive in order for us to do the authentication or the registration so basically first of all we need to register the user before we can actually authenticate them and when they use their user register we need to add their name their email excuse me and the password that they're gonna be sending so what we're gonna be doing now is we're gonna be building our dto for the request body which is going to be receiving a dtos data transfer object is basically the body of the request that we are expecting so inside our models here let me make a new folder just to make it easy i'm going to call it dtos and basically inside my dtos i'm gonna be adding a new class and this class i'm gonna be calling it user registration request dto and basically what what am i expecting from the user basically i'm expecting a string as their name i'm expecting a string as their email and i'm expecting a string as their password and because i want to add some rules so all of these will need to be required so that way in case uh any of the requests coming in without any of these the requests were not gonna be accepted so i'm gonna be required required and this one as well is gonna be required okay great so now that i have built this what i'm gonna be doing right now is i'm gonna start building my authentication controller so right here inside my controllers folder all i have is themes and this that's deleted we don't really need this uh delete all i have is my teams controllers what i'm gonna be doing is i'm gonna click on add controller and i'm going to call this authentication controller authentication controller so now that my controller is with uh i have it here basically what i'm going to be doing is i'm going to see what i have here for a configuration so the first thing is i have a controller base instead of controller and we already covered this while we're utilizing a controller base so we're going to put controller base because basically we're not as a sort review we're not utilizing uh the views so controller phase will give us all of the functionality of a controller without the ability to render any views and that's the exact thing that we wanted and we don't really want this because we are not processing any views the second thing that we need to do is we need to specify a route so it's going to be first just put route and then we specify the path for this route and we're gonna say it's an api forward slash two uh brackets and we're gonna say controller so whatever the name of the controller is gonna be automatically injected and we're going to say this is going to be an api controller and that should be a good first initialization of our controllers so right now if i look at our teams one we can see it has the same thing we have the route we have an api controller and we have we have here the controller base perfect so this one here so out of just uh we can clarify it's going to be this route api forward slash authentication perfect so the next step that we need to do is basically what we need to utilize because we're utilizing identity for us to manage the users we're going to have to utilize some of the identity component that is already provided for us out of the box in order for us to create the users build the uh add them to our database so on so forth so let's do this here so the first thing that we're going to be doing is we're going to basically make a private read only we're gonna utilize the user manager and the user manager is provided for us by the identity uh you get package that we have installed out of the box for free user manager and then here i'm just going to put identity user and then basically we're going to put here user manager and the reason i'm doing this is basically i'm tapping to my di container or basically dependency injection container to get the instance of the user manager so firm remember inside my uh where is it inside my program.cs i have automatically here built the authentication mechanism and basically i'm telling the the eye that i need to use authentication i'm utilizing bearer so on and so forth and basically because i'm already injecting here my db contacts and my db contacts now utilize the identity contacts all of this information will be injected there and basically here i'm using the authentication so that will be allow me to actually uh utilize the user uh manager for identity user to uh create it so you might think to yourself oh okay hold on a second i don't know what the identity user is so in essence identity user is the default user that we that we have in order for us to interact with identity so if we open here the asp.net user table that has been created for us we can see that all of this information exists out of the box and basically this is a representation of an identity user class in essence we know whenever we want to create for example a new table we need to create a class and then we map it to the beta db db set similarly with an authentication we'll do the same thing and this is automatically provided for us so don't have to worry about it so once we have added this the next step is we're just going to be passing the jwt config because we're going to be using it in order for us to authenticate and the request and basically to make sure that the key is encrypted in the correct way and decrypted in the correct way so we're going to put private read only jwt config and we're just gonna say jwt config because we have already added all of this inside our program.cs so let me just open it again and we have automatically added to our dependency injection here where is it here we have automatically added over the eye container it will be able we will be able to utilize it anywhere we want inside our controls or inside our application in general so once we have done that now what we need to do is we need to create a constructor and basically we need to inject these inside our constructor so let's copy this first and basically it's going to be user manager and let's copy this one and it's going to be jwt config and equal underscore user manager equal user manager and underscore jwt config equal jwt config perfect once we have done that now we're gonna start building our uh register action so it's very exciting so let's do this right now let's make this smaller because we don't really need it just taking a lot of space and basically uh our action for the registration because we are sending it to the controller and we're requesting stuff it needs to be post so we're going to say http post and then basically we need to specify the route for it we're going to say register because we're going to have multiple posts requests one for log and one for registration and basically we need to make it a public async task let's say i action result and we're going to call it register and basically what we need to do is we're going to make it get the body from the from body and it's going to be equal to the user registration request dto user registration request dto and we're just going to call it uh requested you very simple let's close this so we'll have more space so here we can see let me make this a bit higher so everyone it will be very easy for us to follow okay so now what we did is basically we created an action we made it as a post we gave it the route we gave it we're telling it that it needs to read from the body of the request and it needs to map to the user registration dto that we have created here and basically uh we're giving it the name request studio very straightforward and basically should be easy so far to follow so the first thing we're going to be doing is we need to validate the incoming request so validate the incoming requests so if we take a look back into our diagram that we did at the first journey which is once we uh this is this for the authentication we needed to add another one for the registration uh which is i skipped my mind apologies for that uh but basically what we need to do is we need to actually validate the requests uh similar simulated this so let's do this right now we're going to put here if what is called model state oops model state dot is valid so in essence this is considered as the model that's being received so we're saying if it's valid and it is basically complying with all of these required conditions that we had we are able to process this request so in case it's right it will continue else or without else we can say return bad request because basically this is an invalid request because this is not valid so once we have done this the first thing that we need to do is we need to check if this is a if the user if the email already exists email already exists let's update this swim lane here so let's do this right now like this let's copy this and let's drag them down all the way down okay so this one here is going to be for the registration so let's so we can just uh consistent so for the registration so what we're going to be doing first is oops uh we're getting the input we're validating it if it's correct or not so if it's not valid we're very sending an involved credentials or bad request we're checking if the email exists or so far everything is the same so if the email doesn't exist where it the difference here is kind of start from here so in case this one is true so the email exists we cannot register it again so we need to say that email exists and we're gonna say this please log in instead of registering because basically the emails already exist if it's false what we need to do is we need to add the users basically we're going to say email doesn't exist what we're going to be doing is we need to validate actually we need to add the email password and the name and once we actually add them we need to send them the database so we're gonna check if they have been saved correctly so if it's not safe correctly we're gonna say it's gonna have a an error happened so error generated and we're going to say bad requests because something went wrong so if it's not saved correctly if it is saved correctly we're going to basically have uh generate credentials for them and basically what we're going to be doing is create a token based on these credentials and then we're gonna give them a first access so they can able to log in so that's that's the original journey that we're gonna take for the registration so first they're gonna provide us with an name name email and password that's gonna be the the first thing we're gonna validate them if not valid we're gonna stop if it's valid we're gonna check if the email exists so if the email exists we're gonna stop and ask the user to log in if it doesn't exist we're gonna add the email and the name and the password we're gonna save them in the database if they're not safe correctly we're gonna send a bad request if it's or not about requests we're gonna send a server error in case it's safe correctly we're gonna generate those credentials generate the token and send them back perfect so just now we are aware of what's going on so right now we are on this phase which is basically we need to check uh so let's make all of these green as soon as not a green blue so make sure that we have covered all of these steps so oops we have checked the inputs we basically did all of these checks now we're checking if the email exists or not so let's see how we can do that we're going to put for user underscore exists so we're gonna actually be utilizing the user manager so we're gonna say await underscore user manager that we currently have dot find by email async and we're just gonna pass the email which is going to be from the request.to.email so this again user manager is this library is provided for us directly from asp.net and this library will provide us with all of this functionality out of the box so this one here we're going to be utilizing to do the lookup so it's gonna be basically if user exists is not equal null we are able to continue actually let's do it the other way if it is equal to null i sorry if it is not equal to null what we need to do is we need to send a bad request so we're going to say return by the request and then say we need to pass new what was the body of the response of the results yeah let's pass an author result to it and basically within that auth results we're gonna say the result was false because it has failed and basically the errors we can say equal a new list and basically inside this list we're going to have a message and we're going to say that inside this message that email already exists that's all what we're going to be doing in case the user already exists so we can see here that in case the email exists which is we have done right now we send a email already exist process so now we need to continue in case the email does not exist and basically we need to add this new user to our application so what's the next step let's make this a bit taller okay so the next step is we need to start creating a user and we're going to be utilizing the identity for this so it's going to be for a new underscore user equal await actually it's going to equal new identity user because basically we're utilizing the default uh default services that the identity frame will give us so we're having an identity user and we're gonna fill the information for this identity user so this identity user isn't expecting an email so we're gonna put a request tto dot email it's expecting a name username or let's put the username similar to the name so we're just gonna put requestdto.email i think that should be fine for not just to create a user so an email and username should be the same and now once we have created an object we need to create this object so basically once we have initialized an object which is of type identity user we need to tell the entity framework that it needs to create inside our database so we're going to say var is created equal awaits underscore user manager dot create async and we're gonna be passing the new user that we have and the way we add it as well we need to add the password for it so we're gonna put request dto dot password so let's hover here over the create user and see what this gives us so let's hover more on top so you can see it okay so if you hover here we can see that basically it create the specified user uh with a given password so that's what we wanted so we wanted to create the user with a specific password inside our table so once we add this the next step we need to check if it has been created successfully so we're going to say if is it created does succeeded so that's what we want to see if it has been succeeded what we need to do is generate tokens but if it's not succeeded we need to return an error so we can say return bad request what can we say we can just say new auth result and basically let's put this here we can say that the errors equal new lists and basically we can add the error that we want we can say server error there's different ways this is just one way we can do it and let's make the request result equal false so we didn't pass and now what we need to do is we need to actually do the work in order for us to actually create the token so what we're going to be doing is we're going to be creating a new method and this method is going to be oops this method is going to be responsible for creating that jwt token so let's see how we can create this method so first of all we're going to have make it private uh we're going to make it return a string and we're going to call generate jwt token and all it's going to take is an identity user and we're going to call it user actually user and basically we're going to be utilizing this method here to generate the token and return it so this should be very interesting and very nice to build so the first thing that we're going to be doing here is we need to create a token handler and basically that token handler is going to be responsible for actually generating our token so let's get started so it's going to be var jwt token handler equal new jwt security token handler and we need to add the reference oh we have two of these okay great and once we have added the token handler the next step is we need to get the security key that we have so var key equal encoding dot utf-8 dot get bytes and then we're going to be utilizing whatever we have injected in the startup class which is going to be the underscore jwt config so let's use this underscore jwd config dot secret and now this will give us the key in the array bytes that we need so the next step after this is what we need to do is we need to create a token descriptor and in essence a token descriptor is we're gonna allow us to put all of the configuration that we need to put inside the token so if we go to our web browser and if we go to our jwt.io website let's refresh this we can see here that a token is formed of different types of data so we have three parts as we said and every single part of this contain multiple types of data so this is the header this is the payload data and basically this is a signature so within a token descriptor it will allow us to input all of this information there so that's what that's what we're going to be adding right now so first things first it's going to be var token descriptor equal new security token descriptor let's add a semicolon at the end so we don't forget and the first thing that we're going to be adding is basically the subject and the subject here is going to be basically new claims identity and basically the claims identity is going to be new array of claims you just make it a new array and we'll populate it like this i think that should be fine let's see let's add for example one item which could be new claim and inside this new claim for example let's give it an id and this id we can make it the user.id okay so let us understand what's happening here so as we said the token descriptor in essence it's going to be all of this information that we have here we want to start inputting it and if we take a look at the payload data that we have here so one of them is the ayat the sub and the name so all of this is basically they are claims and the claims in essence they are like key value pair that we have and these key value pairs that we have will allow us to basically have a key which is basically in this case an id or a name and we can put the value to it and that's what basically a claim is and basically these claims or key value pair we attach them to our jwt request in order for us to have payload data so in essence what we did here is basically what we did is we created the new security decrypter for the subject we have basically created a claims identity which is going to be like a list of claims for the identity and in essence what we did here we started adding one claim after another so as we can see here we have the first claim the first claim is this one so let's try to add another claim so we can for example add a new claim and we can do jwt register claims name and we can use for example the sub and the sub is going to be user.email and if we go back to our web browser we can see here that we have a sub and here it's a token i'm here i'm going to put this up as an email so another one i can do is for example new claim and it could be jwt registered claim names and for example instead of the sub i can put email which we have i'm gonna put also value and we're gonna put user.email and what i can do as well is i wanna so right now i wanna add this yeah which is gonna be a unique id that i have that's gonna be specific for this token and specific for this user as well so specific for the user and for the token so let's do this what we can do actually new claim is going to put jwt register the claim names dot iot actually let's put the jet first gti and it's gonna be a new actually it's gonna be good not a new government and basically we can transfer this to string and we can add it here now let's add yet so we can see here that yet it could be a unix time frame so let's add this so new new claim jwt register claim names dot and we can put the value here is datetime.now.unix the universal time over to let's see is there a unix okay not to string i think that should be fine for now so these are the first information that we want to input which is basically all of this payload data that we have the second information is basically we need to specify the expires and basically here we're going to specify for how long will this uh token lives because what we said is we said these tokens are basically short-lived token and short-lived stock and mean they have an expiry date before they can actually expire and they will not be able to work anymore so let's add this here so we can say date time dot now dot add uh let's make it an hour just next may live for an hour so add hours and just make it for one hour every one hour we need to generate a new token and lastly what we need to do is we need to add the signing credential equal new signing credentials and basically here i'm looking at a new cymetric key and here what i need to pass as my key which i have already created i already got from here and basically once i do that let's see why is it not happy let's see why is it not happy so this would be key and here i need to specify the algorithm and i can put security algorithms dot hmac 256. so that's the security algorithm that i want to use to authenticate all of my requests so what did i do here so that's uh let's cover it again so first of all i created a token handler i then got the key from my configuration my security i converted it to ibyt array i created a token descriptor where i can fill all of my token information so here i put the claims i put the name the email the jet i the yacht all of those information and then basically i gave my token an hour to live before it just expired and then i told my token descriptor which is basically i'm gonna be able to fill this type of information here my hmac and all of this information so i'm telling it that in order for you to get this info we need to utilize the signing credentials and designing credential organization utilize this symmetric key which is this one here that we got and you are going to be utilizing the security algorithm hmac 256 in order for you to get there apologies so once we have done all of that the next step is we need to actually utilize all of this information for us to generate a key so we're gonna put var token equal jwt token handler dot create token and basically what we need to pass is we need to pass the token descriptor so now we can see here how we have actually combined our talking descriptor with the token handler that we have and then we're going to put here var jwd token equal token handler dot right token and we're gonna pass the token here and once all of that is done we just return the jwt token so in essence here once we have created the token we can see that the the type of the token that's being generated is a security token and that type of security token is not actually we can utilize what we need to do is we need to convert it to a string where we can actually utilize it so that's why utilize the token handler here and basically this token handler has a functionality was convert a security document on actual text and that's what we're doing here so let's continue on updating this step here so we're gonna just put var token equal generate security talk generate dwt token and we're gonna pass the new user and basically we're just gonna return ion okay and we're gonna return the auth result we're gonna make it new autoresult and let's see what we're gonna pass inside this auth result so we're gonna pass uh result equal through because it passed and basically the token that we wanna pass it's gonna be the token that we have i think that should be it for the register token so let's do a quick overview of what we have done here so basically the first thing that we have done here is basically we have first created our action and this action basically uh gonna sorry we have configured our controller and this control is going to be responsible to have all of the actions that we need to enable to register and log in so once we have set up the controller the next step that we did is basically we have loaded of the user manager and the jwd to config into our controller so we can actually utilize them and as we said the user manager is basically provided for us out of the box with the identity manager and the jwt config we have done it here inside the program.cs so once we have done all of that the next step is we started building our register controller so the register controller is basically utilizing http post and basically what we did here is we just identified the body that we are expecting and then the first thing that we done is basically we made sure that this body is valid if it's not valid we gave an error and then first we checked the second item basically we followed this hierarchy here let's check it out though first we checked the value then we checked that here the we validated the request format and then we checked if the email exists and if it does exist uh we basically sent the bad request as we started creating the new user we added the new user and once we added the new user we checked if it has been added successfully once that has been done basically we have generated a new jwt token and the jwt token that was created it has been created in this manner here so we can see here that the jwt token utilize something called the security token handler which is going to be the main function responsible for creating that token we have gotten the security key that we have created and then basically what we did is we created something called a security descriptor and here the security descriptor allowed us to fill the body of the uh the body of the token like this and then once we have done all of that we specified an expiry date for our token which is one hour after it has been generated and then we assign a security credential for these tokens so we are able to actually have the security implications here and once we have done all of that we basically utilize the token handler to create a token based on the token descriptor information and then because we we got here a security token what we need to do is we need to convert it to a string and that's what we realize the token handle right token functionality and basically we have a string here and we turned it let's make this a bit smaller it doesn't really make a lot of difference but let's make it like this okay let us just do a build without anything else so let's see here i'm just gonna do dot nut but perfect we can see that the build has completed successfully and we don't have any errors so that's what exactly what we needed so now since we have already created our token to register let's try it out so let's run the application and let's go to our web browser let's see where is our web browser let's come here to the swagger file and we can see here that we have an authenticate authentication and basically we have a new register endpoint so let's utilize that to try it out so let's see what do i want to use so i can put my name as muhammad the email i want to put muhammad at email.com and the password i'm just going to put it password one and let's try this out so if i click on execute so basically i received an error so let's see what's the error it's basically it's telling me that's unable to resolve the user manager while attempting to activate the authentication that's fine let's see why the user manager has failed and let's see what else do we get do we get anything any other errors okay let's take a look at our rider so what that do we have any extra information here so basically what we got here is unhanded exception asp.net identity user manager to activate okay that's fine let us try to fix this problem right now so this error in specific will tell me something real that it's because it says it's unable to activate it it means that there's some kind of dependency injection issue that we have not taken into consideration so let me open up my program.cs and let me see there so what i need to have here is basically i need to add uh identity manager the default identity manager with the you identity user here and i have not done that so let me add this after the identity manager and that i think should be able to fix the issue so we're gonna put first builder dot services dot add default identity and that's the exact thing that we wanted i'm just gonna say i wanna use the identity user which is a default one provided for us i think that should be fine and then basically i need to optimize the options for it so options it's going to be options dot sign n dot required confirmed email account uh i'm gonna say false because we don't really need it because basically at the end of the day this is all a test and then basically what we need to do is gonna put dot add identity or it's going to be add entity framework stores and here we need to specify basically our db contacts that we have so i think it was called appdb context and that should be it so why did we have this so in essence basically we're telling here that a dependency injection uh or basically the eye container that we need to add a default identity manager for the identity user we're not gonna do any fancy stuff with it we're just going to be utilizing anything that comes out of the box then basically we have specifying some options here and basically we're telling it that the account does not need to be confirmed in order for us to sign in uh this is something that we're going to address in a future video where we're going to actually implement implement the sign-in process and the email functionality email verification so once you log in you will be able to verify your email and then once that is done basically we have the identity framework stored which is basically will allow us to connect the identity with the application db contest context because if you remember here we just utilize the identity db contacts instead of the normal db context so let's give this another shot so let's stop this and let's start again let's see where is my web browser and let's try to execute this again so basically the same information that we have provided before and they're still getting a different error okay which is fine at least we are making progress which says unable to resolve service of formula jwt confined by attempting to activate the controller that's fine now let's fix this as well so let's go back and let's stop the application and basically if we go to authentication controller and let's take a look here so it's telling us that's not unable to activate jwt config so let's take a look here inside the program.cs so we have services configure we have jwd config builder gut section jwt config okay uh let's see why could this be an error so let me comment this out and let me commend this out and let us use this private on the eye configuration underscore configuration and let's add it here so it's going to be i configuration configuration and we need to comment this out and let's try this so it's going to be underscore configuration equal configuration and if we go all the way to the end here let us use that instead so we can utilize uh what was it so let's take a look again here something like this so we can take this let's see if this will work so we can do it in this manner underscore configuration the good get section good value so this would need here to be a secret as well so let's try this let's run this okay it's running let's go to all web browser let's execute this and we can see here that it has worked correctly so in essence what we got is we got a token this is our jwd token that we have and basically we got the result equal true it means that the application has generated successfully and we don't have any error perfect this is the exact outcome that we were expecting and this is the exact outcome that we got so the next step is we're gonna be basically creating the login functionality to this so let's jump into it okay so for the login function let's continue so what we're going to be doing is after the register action we're going to be creating the login function and basically first of all we need to give it that out and we're gonna say it's gonna be a login and then we need to start specifying our actions it's gonna be public public async i had a say task we're gonna return an i action result and then we're gonna say it's a login and we're gonna say from body and what we need to do is basically we need to create the body that we should be expecting so that should be fine under the dtos here let's create a new class and we're going to call this class user login request dto and that's going to be very simple so we're just going to be expecting a string of an email and another string with the password string password and we're just going to make these required so in case someone try to send the request without actually providing it the request will fail so we're gonna say required and we're gonna say required and that should be it so now let's just take this class name let's close this one and let's go back to the controller and we're just gonna pass it here so that way we're just gonna call this one login request so basically that's going to be the main form of our login function so what shall we do right now so that since we already like expecting a login request what we need to do is we need to validate it so we need to check if model state is valid so this means that both username and password has been provided it's going to be we're going to be able to continue else we're going to be returning bad request and let's return a auth result and basically for this auth result what we can do is we can say that the errors equal a new list and then basically we can just specify the first one we say invalid payload and then from here what we can do is we can say the results was false simple as that but because it has started uh in case the body of the request has been successful now we can continue and then the first thing we need to do is we need to check if this user exists so check if the user exists and this one here basically if we go to our web browser we're just following up the original plan that we have done so basically we checked the input of the username so that's the first thing that we did and we validated the request and throws out the next step now what we're doing is we're actually checking if the email exists so if the email exists we're gonna continue if not we're gonna stop so let's see it right now so in order for us to do that we're going to be utilizing the user manager that we have injected so we're going to put far we're going to call it existing underscore user equal await underscore user manager dot find by email in sync find by email async and basically here we need to pass the user sorry the login request dot email as simple as that so once we have gotten back the user we need to check if it's null or not so if existing user equal equal null so we need to return what if you said bad request that's correct we need to return bad request new auth results and basically we need to specify within this auth result that uh the errors it's gonna be new list of errors and basically we need to say that invalid payload again would not we shouldn't give out information of why it failed before security purposes but that should be fine and we need to give a token equal false as simple as that so that's one thing that we need to do uh the other one right now if in case the let's go back to the web browser so here we can see the email exists we did an email lookup we made sure it's there so if it doesn't exist to return a bad request if it does exist right now we're gonna continue and check the username and password so let's check this right now so how do we do that it's very simple we're gonna do var uh is correct so basically we're gonna pass the username and the password and we're gonna see if they match the original hash that exists inside our database so we're gonna put user manager dot check password async and this function that is available for us out of the box we don't have to do anything and we can see here it takes the identity user that we have so basically it's going to be existing user and it's going to check the password that it has been provided so log in request the password and here we can see that this method here is going to return as simple as true or false and if it's a valid password we're going to continue if not we're going to stop so let's check this so if first of all it's not is correct so it means it falls what we're gonna be doing is we're gonna return uh word request new auth results and then basically even gonna turn new it's gonna be errors new list we're going to say invalid credentials we're not going to we're not going to give any further detail i'm just going to say the result equal false and why is this not happy because here this needs to be awaited we did not await it okay perfect so that's the case in case it's not correct but in case it's correct what we need to do is we need to generate a jwt token which is basically we're going to be utilizing the same function that we have created earlier and that's going to be the main point of reusability of that method that we have created so in case it's correct it's going to be very simple we're just going to be basically trying to find that token so we're going to put far jwt token equal generate 3wt token and we're just going to pass the existing user as simple as that and now you can see basically we just got the token and we basically reused this method that we have created earlier and all we need to do is just return okay and basically we're gonna return an auth result actually a new auth result and basically within this new auth results we're gonna basically return the token so token equal jwt token that we created we don't have errors and the result should be true as simple as that and now let's try it out so we have this here now let's try it it's building and it's running perfect okay it's not happy oh i think we have an issue here and because we did not specify if this action is a post and that's something i have missed so here we need to make http post because this is a post action so now let's try this it is happy now so now let's go to our web browser so now basically let's update this so we did the validation we did the validation of the combination between the username and password we validated the credentials and we generated the token if it's successful and if it's invalid we just sent in by the credentials okay we have already completed all of these so now if we go to our swagger let's just take the this because i will not remember the password so let's refresh here and now i should see two actions available which is the register and the login so first of all let me just just re-put the information here just so i can keep track of it but let me take these two because i need to use them to log in so here i'm gonna put try out and i'm just gonna pass this one here the email and the password that i have and now if everything goes to plan i should see a jwt token response so let's check it out so execute and basically we can see that everything went to plan and we have we were able to actually get a jwt response and our we got our token back exactly the way we wanted which is great this is the exact result that we wanted now now that we have basically created the registration we have created the login we're just gonna right now attach the authorization to our other actions so here right now if i click on get or for teams for example i get on try it out and click on execute i will be able to get here without me actually having to pass any of the authorization so let me open insomnia and let's use insomnia because it will allow me to attach the security header there so i'm gonna basically uh i think this is too small let's create a new collection i'm just gonna call it uh [Music] both requests but let me see if i can make this a bit bigger so i'll see insomnia preferences and maybe the font size i'll just make it 34 for now and basically the editor font size i'll also make it 34 oops 34. so let's see if this will help is there a way i can save it okay i think that's better now we can see everything is a bit bigger yeah so what i'm gonna be doing right now i'm just gonna click here new request i'm just gonna say this is gonna be the login request it's gonna be of type post and the body is going to be json create so here what i'm going to be doing i'm just going to create take this url where is the url for the login this is it so let's take it i'm just going to paste it here i'm just going to paste the body and i'm going to send the response and we can see i got the token great and let's add a new one and this is going to be for the register so just keep them both in our insomnia it's also going to be post the body is going to be json create let's take that url for register let's make this another one so call it i don't know user and here we put user one and the password just add one one to it again okay let's take this url let's put it here let's take this body let's make this here let's change this to 2 to 2 for example if we send it now we get all of the registration correctly so these are the two ones that i want so what i'm going to be doing right now is i'm just going to try to take this one as well which has got where is it this one get the teams so right now i'm gonna just add a new request i'm gonna call it get themes we're gonna make it as cut and we're gonna create we're just gonna pass that and send and we can see here i get it and you notice here in the header they are empty i don't have any authentication header i don't have any security premises i don't have any of that so what i'm gonna be doing right now is basically i'm gonna prevent access to this action unless they have provided the correct jwt token that has been generated so let's see how we can do that so let's go back to our rider and then inside our authentic stop this don't want it running around so what i'm going to be doing is i'm going to go to the teams controller and i'm going to update it in order for me to take advantage of that so on top here before the route i need to add one single line so that line is going to be authorized and basically authorize mean here that it needs the user will need to have some kind of authorization and that authorization is going to be our jwt token and the way the application know that this is going to be part of the jwt token because inside the program.cs here what we did is we have injected our security authentication to the middleware and that's going to be the default if you notice from here that the full authentication mechanism is going to be that so that's going to be the first part that we need to do is basically add the authorized here and then we need to add more configuration to it and basically it's going to be authentication scheme because we already find that but we need to specify for this specific controller what type of authentication scheme that we want and all we need to do is we put jwt registered jwt it's not this one this needs to be jwt bearer default if i can type [Music] defaults dot authentication scheme and that's what we the first thing that we need to do is basically specify that this actual controller is going to be authenticated through utilizing of jwt better tokens and basically all of that we can see it already set up here inside of our program.cs and we can see here that we have the jwt better defaults and this is going to be the authentication scheme and that's the only thing that we need to do so right now if i try to run my application again and if i try to go to insomnia let's go to insomnia and i'm gonna run the same this one again i should get a four or three unauthorized so let's see i've got the photo one excuse me a 401 uh uh for one unauthorized which is exactly what i wanted because i have not passed the right uh header to it which is telling and telling this request that is expecting a security header which basically tell it which user is trying to try to access this controller so what i need to do is basically i need to add a header which is called authorization and basically because we said the authentication scheme here if we take a look at the controller if we take a look we said the authentication scheme is very default so that means that we need to put bearer which is the type and then i'm gonna take this nice token that has been generated for me i'm gonna go here i'm just gonna paste it after bearer and all i need to do is that so right now if i click on send we can see that i was able to get the response back exactly the way i wanted and basically right now if i try to remove this and send it again i'm gonna get 401 if i add this send again i will be able to get it so again here let's use another token so this one i use for the login and if i come here and if i update this token here with that one token and if i send i should still be able to receive it great so that's in essence here what we have done is we have covered the full scope of our application so first the first scope is uh that we have added the login and the registration and basically we have implemented a token based authentication inside our application so let us do a quick summary about what we have covered today so the quickest way that we're gonna do it is we're gonna go back to our web browser and we're gonna explain it through the diagrams the swim lane diagrams that we have so let's go back to jw to our draw.io and basically here what we have done is basically today we have created two journeys we have created the registration journey and we have created the login journey the registration journey we allowed the users to input their email their password as well as their name in order for us to create their accounts and then basically we have utilized the identity provider which is going to be the microsoft identity which is provided for us out of the box in order for us to get there for both the registration and the login and basically what we did is we went through all of this journey so for the registration journey is basically we took the credentials from the user we validated them we checked if they already exist or not and based on that we continued or we stopped so in case the email exists we we asked them to log in if not we basically validated that email and then we utilized them to generate to save them in the database so if they saved correctly we'll continue if not we sent an error and then based on that we generated token and we sent it back to the user on the other hand for the login process what we did is basically we took the credentials we validated them we checked if the email exists if it didn't exist we said invalid credential if it does exist we continued with the journey and basically we were able to excuse me generate credentials based on that and at the end of it we basically granted them access utilizing jwt token and inside the code we have utilized those libraries which is basically the nuget packages that we have installed in the beginning to allow us to utilize this by injecting them and configuring them inside our program.cs so we can see here for example we have uh basically updated or basically taught the application that we're going to utilize the authentication we have taught the application that we're going to be utilizing jwt bearer token we have identified that the characteristics of our gentility barrier token here of what should be valid or not and then basically we have injected it into our dependency injection so we can actually utilize it as well we have utilized inside our controller so we can see here that we have utilized the user manager which is another built-in functionality from our identity framework to get here i hope this video was helpful please like and subscribe if you like this video it will really help a channel have a great day
Info
Channel: Mohamad Lawand
Views: 25,796
Rating: undefined out of 5
Keywords: json web token, token based authentication, .net 6, .net, api, beginner guide, step by step, c#, dotnet, dependency injection, coding, ef core, sqlite, database, entity framework c#, entity framework core, entity framework, asp.net core tutorial, api security, jwt token authentication web api, jwt authentication in asp net core, jwt authentication, json api, dotnet security, web api jwt authentication c#, web api jwt token authentication, rest api jwt authentication
Id: Y-MjCw6thao
Channel Id: undefined
Length: 113min 48sec (6828 seconds)
Published: Mon Jun 27 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.