Build Secured .NET 8 APIs With Custom JWT Authentication & Authorization using Identity Manager! 🔒🚀

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone welcome back to net code H Channel  I am Frederick and I'm very excited to have you   here today you know security to Applications  is very very important and when you have your   application you must have a mechanism to protect  it especially when your app has a in connection   with database uh to precise web API how can  you protect this ESPN team has made it possible   for us to use an identity manager an identity  manager support the cookie based authentication   but in this video we're going to look at how  to authenticate and authorize users using GWT   authentication with identity manager so instead  of using the cookie based authentication no we're   going to use an JWT authentication instead maybe  you're asking yourself why are you going to use   this JWT authentication first of all JW stands  for Json web token it is a string of characters   combined together which comprise of the user  Identity or user claims the claims could be such   as user ID maybe username user row and Etc now  this token is been generated from the server and   now push it to the client that is uh specifically  Blazer web assembly now after receiving this token   it has to store it in somewhere a safe place  such as the local storage or session storage or   protected storage after storing this what you're  going to do here is anytime that you want to make   a request to an API you just have to add this  token to the header of the HTTP client before   it can make a request the reason why it has to do  that is you know when you create Json web token   the server becomes stateless meaning it doesn't  store any information of the user so any request   coming from a client to a server has to fulfill  all the has to contain every information that   the server would need to authenticate the user  that is where you need to specify these claims   attached to the strength token when sending it to  the API but with the cookie base it is the server   that issued the cookie and now sent it to the the  cookie session of the browser straightforward it   hasn't give it to the client but here we going to  receive it from the client we're going to store it   and anytime that you want to make a request we're  going to um add it to the header as usual before   we jump into this make sure you have subscribed  to this Channel and also hit on that notification   Bell so you never miss out any of upcoming content  and also if you enjoy what you're going to see   today please do not forget it's very important  to give this video a thumbs up it really helps   this channel grow if you want to support us to  uh by buying us a coffee we going to accept it   thank you so much thank you in advance for doing  that check out the video description and I have   it over there you know this project is going to be  in two FS maybe first of all we're going to talk   about how to authenticate and authorize um user in  a web API using identity manager that is talking   about net 8 okay and later video we're going to  talk about how to consume this API authenticated   API inside our Blazer we assembly application  but I believe you can do that if you can do that   please put at the comment section there and I'll  have a video done on that okay I offer training   session for people who are interested in Blazer  and net Technologies talking about the Blazer   which comprise of the Boost um both hosting  model and also net mary.net Mar Blazer hybrid   for mobile application so if you are interested  please check the description there's a mail that   you can write me through it so at the end of  this video you must be able or should be able   to create your own custom authentication using um  JWT weight identity manager in web API so let's   jump right into it let's create a project here  and I'm going to name it as democ custom. net   a Blazer web authentication and authorization  with identity manager solution actually we are   not adding a Blazer yet Blazer or assembly yet  but maybe in a later video we going to talk about   how to um consume this so it's better we add  it to the name space okay so let's create it   that way now when you go to gab there's going  to be the name that you can be I'm looking up for so I'll go for blank solution so that's going to be the solution name now we have our solution created now let's  go in there and I add our um web API and that's   going to be identity manager server API so we  go to solution Explorer then I click on the   solution the empty solution that have been  created and I click on add new project and   we're going to choose web API so I have one  over here I'm going to choose as. net cor web   API and now the name is going to be identity  manager server API so now let's add to the project so that is a net 8 make sure you choose  that now since we're going to create a customized   authentication type so we didn't not to specify  any type here let's make it as none now click on create so now that we have our server API  identity manager project created what we're   going to do here is since maybe later video  we're going to learn how to connect this or   consume this API in an Blazer web assembly and  it is very important to put all the classes or   the models that you're going to be using both  in the server and now the client section in a   class Library so you can be adding this to the  project and I can also add it to the same the   other project that you're going to be created in  the next um video or in Future Okay so let's add   this um let's go to solution and now let's add  this project and this is going to be a class library and that is a class library for  C and I let's name it as shared class   library because going to be used by the  API and then the Blazer um web assembly   too you make sure the framework also the  same as 8.0 click on create to get it created so now that we have this created  what we're going to do here here is let's   clear this and now we're going to add this C  class to the server API project so we click on   the dependencies in identity manager Ser API  and I go to add project reference and I here   make sure you choose the class that have been  created now and I click on okay to get added   the next you do here you're going to install  some packages that we're going to be using for   our EF migrations and our databases and D tokens  and JWT and a whole lot okay so going to install   them inside This Server API so this what I'm  going to do I'm going to right click on the   Ser API and I go to unload Pro project now let  me save this now in Project settings I'm going   to have access to this item group where I'm going  to have package references now I'm going to paste   this and these are the packages that we need we  need authentication JWT we need EF core and we   need xql server tools for migration we need  tokens for the GWT we also need the Swatch   Backle and also for the filter to give us the  UI and also able to authenticate when we have   authorized attribute on top of our controllers  and we have this okay so these are the packages   that we need so pause the video and I'll try  to install them one after the another I have   installed them already that is why I just have to  copy this or even when you able to when you have   these references you have to paste them here and  you have to reload and now everything is going to   work okay so if you're not pause the video now try  to install these packages all right I believe you   are done now so can we continue on yes of course  let's so let's save this and I'm going to reload   this project with dependencies which going to  install this or restore this packages to this application so I'll just go to solution right  click on this server and I go to reload project   with dependencies to get this is reloaded okay so  I'm going to have this you see restoring packages   and it's going to restore them so once you  are done with this the next thing they're   going to do here is we're going to create our  appdb contest class and this class going to   inherit from the identity DB contest which is  an OP uh optin class which contains all the   table names and the various columns I'm going  to be using for this identity management okay   so let's go to the server section and we're  going to create a folder here and I name it   as data so this is an API server right click  on this let's add a folder and I name it as data let's create a class to this and the name of this class is going to be   the abdb contest so here it has  inh from this identity the beon test so this is coming from this idty EF and now  with this control period we can now create a conru   for this but instead of that you're going to be  using we're not going to use aate 8 as introduced   that is a um primary Constructor so here that is  C version 12 so even when you click on this we   see we have control period you use primary  Constructor and very simple one so that is it now when you take a look at this identity  DB context it has a relationship with identity   user identity user compris of the usern name  and the ID okay so maybe you like to customize   it by getting the user name user address um  user information that you be needing uh maybe   later on so we're going to do here is you're  going to create a customizer you're going to   inherit from this identity user so let's  go to the same place folder right click   and now let's add a new class and now  this new class going to be application user so this application user is  going to inherit from this identity user okay now in here let's specify some  customized property that we're going to be   using so we need string and that would be name  and maybe you're going to have access to what   else again address let's maintain this okay  so let's maintain this maybe if you want to   add any extra one then you can put it down here  but for now you want to get name because when   you check this identity user if I click on a  peep definition here check what it ENT tells   it it has this username right so username here  is going to be the email and I also specify the   name as well so the person's name going to have  a person's username it has phone number and Etc   but for now we want to maintain that so let's  close it up so we have this let's go to the   abdb contest now in here we can specify an option  has indicated here okay so with identity contest   let's specify a t value and that's going  to be the application user that we have created okay so we are done with that okay very  simple one we didn't know to create any database   for that you know when you hear it from DB contest  you have to specify database table name in the   various columns by specifying the model that you  want to use for but for now since it's herting   from this identity it is an optin model which  comprise of the various attribute that we we   have have shown you and that's what going to use  for the database so here don't do anything again   just leave it as it is okay so let's save this  what to do here is let's create our connection   string and you know we can do that from the app.  Json so let's specify our connection string in here so let's give the name as default connection  and maybe we can specify our server equal to local   then you're going to have our database is  equal to demo identity DB and maybe let's   have so let me use custom one and add so custom  demo identity DB that that's fine right okay so   you can give it any name that you want now let's  have trusted connection and now let's set this to true and also in net Serv and  above you have to trust server certificate so set this to through  as well that's all once we are done   let's register this connection string  in the program.cs file so come here   before the app build let me give  a V Space here and I'll specify starting then maybe you're going to have end then  right okay so in here let's have our builder. services that services do rdb contest specify  our abdb contest class that we just created and   now in here it needs a parameter so let's  specify an options here and now with this options we're going to say options.  use SQL which inh from the EF code   that we installed then here we're going to  specify the connection string so Builder   do configuration. get connection string then  this let's specify the name of the connection string and that is a default connection so to make sure we are doing the  right thing we can just come here grab this   and now save it you know copy and paste is  very important it help you skip some errors   I you see this default we made respect it  wrongly so let's create it from here copy   this save that and I go here and I replace it  fine now here let's handle in case this is not   found so we're going to use in case this is not  found then we want [Music] to this should come here so you want to throw new reception  and it's going to be invalid operation exception and we can say connection string is not found so it's good to  handle errors anytime so as soon as   you have you see this you know where you're  going to okay all right so we have this set   uhbe you can put this in the next line  in this format let me increase okay so   now that we have this set come down here  we have to add our authentication so add authentication and this is not just authentication  but rather it's going to be JWT let me be specific   isn't it so we have in two F the first one here is  going to be identity and also JWT authentication   so add identity and JWT authentication okay so  this is going to be the first one is identity   and now with identity we're going to have  builder. services so do add identity now this   identity has two models that it has to take  that the T values the first one going to be   an application user and you know the user that  I'm talking about I hope you remember it isn't   it that is the extended class for this identity  user class after specifying this you to specify   the identity row so with the row since you're  going to be adding rows to it okay we can also   um extend the row but for now maybe if you  want to add more info or more properties you   know basically the row has just the name the ID  the name the the normalized name the concurrency   and Etc if you want to add maybe another info to  it then you can extend that but for now it is out   of the scope so let's have identity user is it  user or row so this is row because user can be   found in the application user so you need not to  um specify this anymore all right so once you have   this we going to be adding the next one and that's  going to be add Entity framework store and now we   need to specify T value that's an application DB  contest class it's not application rather it's an   app DB contest class isn't it so appdb contest  class I believe you're not doing what what I'm   doing right they're doing the right thing okay  so aside from that we have to be adding signin   manager because we going to be using what you  going to use signin manager here well well well   we're going to be using Okay so let's add it  for maybe um later on we're going to have a   look on this but for now we can decide to skip  this signing manager because I'm not going to   actually use signing manager I'm going to  use user manager okay so you let maintain   this before let's add um rows because row is very  important and now you have to add this identity row Okay so now we can terminate this so  control k d we save that so this identity   now let's go to the JWT authentication okay  so with this one what we're going to do here   is going to have also our builder. services  so add authentication and authentication you   know it need to specify some options in  here I'm going to say that this options so we're going to have options dot so let's  have def default okay so you need default   authentication scheme so here and now this is  going to be JWT default dot authentication scheme   the next one we're going to have the same  thing so option dot default Authentication   or this time going to be challenge scheme is  equal the same WT default do authentication   scheme so you make sure you specify this  else when you try to make a request to an   API you're going to have 404 in of 41 when  you put an an authorized attribute on top of   the controller if you don't have this you're  going to have 44 okay and that's going to be   not found but this the actual sense here it  is found just that you are not allowed and   to be 401 so you make sure you do this aside  from that we going to be adding do add JWT   barer and now with this beer it also needs  an option I believe you've seen that isn't it so this also needs options so let's specify  this option Dot and now the first one to do here   is token we know you can see we have token  validation parameters and it's equal to new   so token validation parameters then we can open  this and I specify validate issuer so we have   validate issuer we set this to true we can also  specify validate audience set this also through   then maybe validate signing key so is signing key  you said this is true and validate lifestyle so   it can check if the token has expired or not we  also set this to true and now let's specify the   issue and the audience so validate not validate  rather it's supposed to be valid see we have   valid um issuer and our valid audience so let's  have the first one here going to be the valid issuer okay let's see so right issuer then we need to  specify Builder do configuration then   this configuration you're going to create  a section and this section is going to be   JWT and in that you want to have a key value so  the key here is going to be the issuer okay and   now with this let's make a duplicate of this  instead of the issuer here you're going to be audience and now with this  audience going to be also an audience okay now after specifying this let's have   a issue ass signing key and this  equal to new symmetric security key so symmetric security key that is this one  and you have to encode this so we're going to   say encoding which is coming from system. test  so do utf8 do getb so we want to get bite of   this Builder dot not service rather configuration  and now the section is the key no not that key the   session is JWT and now the key here is going to  be the key okay so we want to grab the value for   this key and now since we can return n we have to  make sure we make it inable form all right so this   all that we need to have a token work control k  d save this and we can now move forward now the   next thing here is you know we are going to  allow oh we are going to use swashb that the   the Swagger and when you have the controller  being attributed with an authorized defitely   is going to allow you to perform a free or any  much request unless you come in with a token   so in order to add a token to the header of an a  request from the Swagger we have to specify you   have to pass in an option to the swaga service  okay so defaultly swag has been registered as   soon as you create a new web API project  you see that over here by this time around   you're going to move this and down here you're  going to specify it here so adding swaga so add authentication to swaga UI okay so with  this and not to let me just grab this from here so this is very simple that we are using  you see we add the same of services swag gen   now this swag gen compris of I I think three  component the UI it has a gen and it has uh   one one addition yeah we know here we adding the  security definition and there's an o or two and   now here you see we want to specify the scheme  here and where do you want to add the token to   in the header what should be the name of  authorization what should be the type is   an API key okay so that's what we are adding and  that is all all right so we are about to finish   this okay we don't want to so here control K  we can just simplify this and when you come   down here you see we have an authorization so  we have to use an authentication first so app.   use authentication authorization this is the how  it must follow so take note all right so we are   done here okay we are done what we're going to  do here next is we're going to create our rep   repository going to create our interface  and our repository but before that let's   save this and add database migration so we can  have the tables created for us so let's build it first so you know that You' SE is suceeded so  go to package manager console and let's add   database migration to it so add migration  and this is coming from the EF or tools   package that we installed so let's give  it any name at all I say first so let's   wait for it to get built and it's going to  run all the query for us so this should be   API it must be the stup project let's  see so we have an API surveys as start   up that's fine package manager console  it is set over here now you can do it again you can see that it is done now so we  have a file created and that is a whole table   that we have you know we did not specify any  table name like this it is an op in from the   identity manager so it has all these available  tables in there and that is what the next code   next line of code is going to execute this into  a real thing okay in a datab that we can see so   with this we're going to say update Das database  and now let's run this going to run all this using   this SQL commands it's going to get this created  so you can see w we have this issue let's go to   solution now click on the same project here and  now this set this to forse save this let's read again yeah so it is done now so when you check  our database you're going to have access to this   remember the name here it is custom identity  Etc let's see so SQL Server now I go to my   desktop databases and I can see I have this custom  custom demo identity DB that is this one so if I   open this tables I'm going to have a whole lot  of tables in here created by the opin identity   manager let's wait see we have them here where I  want to focus here mat is the identity user this   is the first table that we need the one here is  identity row async you're also going to use this   so let's open this as well the last one here is  you're going to be using ASP net users row which   going to comp price of the rows and the users  so we have this that's fine now let's check and   see so we see user ID and arow ID user has no row  there's no user here which has a row and there's   not even a row ID there check here this is a  row see it has the ID name normalize name and   concurrency stamp so here if you want to specify  more options or more info on this that is the why   you need to extend this identity Ro class we did  not do that okay when you check this esp. users   you can see initially it was having a usern name  here but we extended by adding name so it has in   here and that's why we made it as application  user right okay and that is all so you can see   we have these three tables and that's what we've  been looking through or be watching this for now   it is empty now let's go in and create a rippo  so you know we're going to be using since later   video or future video we're going to be consuming  this API or this identity inside an web assembly   project we like to create create an instance  or one public repository and that's going to be   one public interface okay then you're going to  be using it both in the client session and now   in the um AP identity session you know where  we want to skip repeating ourselves because   what you're going to be using here the same as  what you be using in the client section so why   don't you put it in the sh Library so we can  share among the two that's a good idea isn't   it let's do that so we go to solution and I  you see in our library right click let's add   a folder to this let's name this as contract  which is interfaces so contract and now this   contract we want to give it an interface here  choose interface I user or I user account it's   an interface because that's why added I okay now  with this we going to be let's make this as public   we can just clear this to make the class simple  or the interface let's save that let's create our   models first so we need to create our models  and now here it's going to be dto because we   did not create any database so all the mod going  to be creating here it is a dto that is a data   transfer object that's going to transfer data  from the client to the API that's fine okay so   let's first create our user okay so we're going  to have maybe that's a that's going to be user dto so solution now let's create another folder  here and name it as dtos so folder dto let's add   one model to this and I will say this user dto so  user dto you want to have access to the following properties so let's make here as public you can clear this okay so we need an ID ID is not going to  be required because when creating an account   you don't need to provide any ID unless you're  retrieving an account from the database that is   where you're going to use an ID so we don't want  to make it as required we have name we have email   password and a confirmed password and I see we  using this confirm n. net8 you can use this name   of instead of specifying the name of this property  in a in a in a double code here you can now use a   name of with reference to the property itself okay  so now we have this um user can't you also have   our login dto yes you can so let's also specify  our login dto because then going to be logging in   as well so add your class and that's login dto you  know this is going to handle only two properties   the first one is going to be the email and the  next next one or the last one is going to be the password okay so declare this all right so we have an email and we have  our password we save that now definitely when   you create this you're going to return a response  when user registers you have to return a response   the state of the process was it successful or  error occurred whilst creating an account for the   user so in doing so we have to create our service  responses okay so I'm going to create one giant   class and I name it as Serv respon which going  to contain multiple responses so this going to be   the same D2 going to be using for data transfer  or information Communicator so we say service   responses and now in this service responses we're  going to create two records or record class first   one going to be the general response we're going  to be used for the General type and the next one   here is going to be the let's make as public it's  going to be limited to login response we going to   handle with token so after user has been created  you have to generate token when us tries to log   in and you have to return this and now maybe we  can add message to it okay that's fine let's save   this so we have this model is created okay and  the one last left here it is a user session you   know when it gets to the app session or when it  gets to the client session definitely we need a   mechanism to handle this and I'm St but for now  I don't think it is necessary to use the user   session but well let's try and see maybe going to  be using this in our repo so let's our us session   class created in addition to this and that's what  we're going to using to prepare the the user info   for token generation Okay so let's add a class  here we see it is user session which has for properties so it's a record class and on this  record you know we are using ID name email and   our row this what we're going to use to populate  our claims so in our claims we're going to have   access to the r the ID the name the email okay  so let's save this now our model are well done   created what we're going to do here is in our  interface where we have this is interface okay   this is in the contract folder from the set  because going to be using by both the future   client I'm going to create and also the current  API that we have so in that we need to specify two   method for now we are focusing on only creation  and our login so account creation and our login   so you see from the create account we need to  use a general response because here there's no   return type of token but it gets the login we're  going to have a token so we have to return a token   these are the various payloads that's fine so now  we have this the next we're going to do here is   we're going to create an implementation to this  now here we are using a separation of consent   what do mean here is we don't want to put in code  which is not necessary um um to be used by any if   it is limited to one object or one uh project  why don't you create it in that sub folder in   that project instead of putting it in the shared  you going to put in the share it's going to be   added to the client section meanwhile the client  also do not need that so let's put it limited to   the server so here we need to create a reple so  let's create a folder here and I'll name it as repositories and maybe you be asking me what  is repository it is just a class which contain   definition of an interface so here let's right  click let's add a new class and I is going to   be an account repo account Repository now this  account has to inher from the main interface that   is the I user account and our contol period  we going to extract the interfaces in it okay so in here you know we we not you can use  the appdb contest class because it doesn't have   any um table to work with all the tables  are inherited from the NDB contest so in   order to have access to the account tables  that we have in the database we have to use   user manager and R manager specifically user  manager going to have access to all the tables   and the columns that we have so we have to  inject them here and know with the help of   this um primary Constructor you can inject all  of them on top here so instead of having this   creating an a Constructor and injecting them in  here all that we need to do here is to create   a constru the name of the app passing this um  bracket here and I'm passing the user manager   which in here from application user take note  so this is extended class that we created for   this identity manager that's identity user and  now we have this rle manager for identity row   and we have this ey configuration to access to  our config file okay now we have not set the   configuration yet so we have to navigate to  the app setting. Json and now in that we can specify this solution up setting. Jon now in here let's  specify GWT as a section name these are the keys   and these are the value but here this port is  not the accurate one you know this must be key   and the minimum number here must be 16 it must  be kept safely because this what you're going to   be using for authorizing the user so here we  have this issue and to get this the accurate   Port go to solution properties line settings  and can see we have the port in here where we   go for the https it is 7202 let's grab this go  back to the absent and I'll paste it in here so when we have our app the client created the  client p is going to be the audience because   that's going to receive from this and now the API  is going to be the issuer so communication happen   between the issuer and the audience okay so we  have this so everything is set here and that's   what we having this eye configuration so we can  retrieve the data from that section now when you   get to create an account this is all you want  to do so when you get to create an account we   first have to make as an async because what you're  going to be using here using the identity manager   must be an asent task and in here we're going  to have access to this let's have a look here   we are checking if the Modo come in is if the  payload is null then return Modo is empty if   not then you want to create new application user  okay so I'm going to say this is an application user so you're creating application user and I new  application user has in the following property it   has what this name email password hash and this  username so if you right click on this you know   this is an extended class it has just a name but  it is it is inheriting from this identity user if   I right click on this and I go to peep definition  it also has this identity user okay and I could   see it has this username now let's see so if I  go to Iden user p definition it will say it has   this take note to F enabled phone number phone  number can see has all this email and username   Etc okay so that's what it's having or it is  using let's close this so we can extract this   from the interes all the properties in there  and now from the password hash we need to to   specifying the raw password because this system  is going to encrypt this so you can see it get   or set assorted and our hash presentation of the  password for this user so there's no need to use   any bcrypt to encrypt the password no this going  to do it automatically for you isn't not nice yeah   very simple so after Gathering or populating  the user as an application user there is what   we're going to do you're going to check we're  going to find from the database table so in a   normal sense if you're using a number database  using the DB contest class you have to get it   maybe user equal to maybe appdb contest. user.  first or default async where the user email to   the email coming in a whole lot but using this  identity manager just simple of course going   to make it happen we get it from the database  and check is the email there already if yes   then user registered already but if it is not  there then you want to create the this user   so it means you want to add and save it so by  creating you're going to pass in the user that   we have gaed over here and I pass in the current  password now Al it's going to this also going to   set it or hash it for you this is a raw password  it's going to Hash it as this password has done it after doing this you can now check it's going  to return um a Boolean expression here is this   sucessful or not so we're checking if it is not  then return error C and here we can handle this   error what actually cause it because user IMA is  not found and it has problem so maybe you can log   this and now extract the the message here you  can extract the description from this okay and   this can be done from using this created user  and you can have an errors in here now select   so you see when you I click on this I have this  dot we have errors here so this errors contains   all the error that made this couldn't work we can  extract it and now store it somewhere or now even   send it to log it somewhere for an external check  Okay so if this gets created meaning if sucessful   created user is created then you want to assign  default row now here to assigning row you want   to check we're using only admin and our um um user  okay so you first find check if this R name exist   if admin exist it means that somebody has been  registered as an administrator already and admin   has registered once in the application later on  you can manage users you can add more admins you   can remove move you can delete admins and Etc  or users or R but for now you want to check   if admin is there already it means it has been  created because the first person comes in has   to get a a r created and I'll assign that Ro to  that person that's all once the subsequent ones   must be added to a user row if user row is not  created then create it and I'll add so here you   first create over here if it is it is not found  and I'll add a current user return account created   if it is not if this is created already it me  admin is already there then all the subsequent   are going to be added by user so check user is  there if it is not created and I'll add it so if   it is not there create it if it is there then  straight and I'll add it and I return account   created that's what that we are doing in here  isn't it that's is it so let's save this here   and I make sure before we run this application  we check our tables here and I can see when I   refresh it empty have I believe you've seen that  have you also check yours you have the same thing   isn't it that's fine now we going to create our  controller so we can um run this now let's go   to the controllers folder and I'll see let's  right click and now let's add a new controller here so this going to be an API make sure and  you need an empty one maybe you can go in for   the the crowd one that you can just create and  do St but for now now let's have it this um this   one as an account controller so the r is going  to be API SL account that's right now when it   gets to the registration this so we you can just  create one end point to handle this registration   so in here this what we doing and I we have to  inject this user account and you know with the   help of net 8 or C 8 we can now work with primary  Constructors so instead of creating a Constructor   from this here now injecting and initializing  no don't do that again it is a kick this one   very simple one I'm optimizing our code okay so  we have this all right set and now we call this   return and okay because as soon as it able to  get connected to a service it means connection   is established but maybe you're going to  have an error which theor going to contain   by this response okay so you want to return  it to the user because here we did customize   our own responses that we want based on the  stages so we we have to return okay as soon   as that respon is available get it to the user  so let's see now we have this let's find this   application and see if we've done everything  correctly for a registration to be done let's see all right so we have our account here let  me Zoom it okay I believe you can see that   isn't it that's fine we have is an authorized  attribute or authorized feature that we added   to adding authentication system to the swaga by  installing this package swb do filter package   so we can have this now let's register this in  so click on this try this out and now in here   let's see if I passing the same user at email  now let's passing password over here as user   at one 23 This is My Strong password ever so  user at one 2 3 so test yours when you're done   click on execute now let's see the response  is it going to have account created if yes   it means everything is working oh my God now  you can see from here we have this error and   is saying something unable to resolve service  for the type this and this and this and that I   believe you know what this is talking about  right as soon as you see service what comes   to mind di dependency injection and we did not do  that we forgot so let's go and do that and we can   do that quickly in that program. Cs and in that  we need the interface the general interface and   our limited um class implementation class  or the report that we have just created so   we go to quickly solution now check here have  you seen this program click on that and I may   be down here we going to add this ascope I user  account you know this an interface that we just   created and this the the repository that we  have save this and I believe everything must   work out now now so let's quickly check  it up you have to rebuild this I believe so okay so let's try this out again and  by I'm sure by now there won't be any   issue anymore so user art one two three  have we tried yours did you get it let's see that's fine so we have it account created  now let's quickly check was it created for   administrator or user because you know in set  modus we said that the first person the first   account must be assigned to admin the rest must  be assigned to what user let's quickly check so   we go to this ESP net users let's refresh this  andely going to have this user in here exactly so   you can see we've seen that that is this one and  now you can see from this that we have the ID of   this user is I believe you cannot see this isn't  it but how can see that it ends with 9 e let's go   to the rows Here and Now check do you have any  row admin row created yes of course there an   admin row and ented 09 let's go to aset rows and  I'll see the kind of row that the user has is the   admin yes you can see the admin here it is for 09  that's a row ID and now the admin person here it   is 9 e so defaultly the first first person has  been assigned to a row ID of an administrator   and now we have one administrator one row created  that is this admin let's register the next person   and see what going to happen next okay so here  I'm not want to do anything much I just want to   go there and I'm CH and add just one to it it  turns it out click on execute let's see okay   so then we have the same thing account created  Now quickly let's Che it up so if I refresh this   you can see we have a user created and now the  ID here if I check it is 021 let's check user row so as net users refresh this and we have  2 a for the second person let's check the as   net row user ID row ID refresh this and  now who is inheriting 2 a 2 a 2 a let's   see so let me expand this 2 a that is what the  the user that is a rule ID so we can see all   the subsquent users are going right said  here if I if I decide to add the last one see let's make this as two execute this done let's check it up if  I refresh this still going to happen so we   have one C that's this the user and now 02 one  so 021 it is for the row if you don't believe   me let's quickly check the row which end 021  that is a user you see so all the subsequent   registers are going to have this ID of user there  is the role of user only the first person could   be assign as admin but for now this what you want  to have our model to contain okay maybe later on   you can customize yourself and um you can add  multiple admin to can add users you can revoke   a user Ro and Etc a whole lot okay so now this  work let's handle the login system so let's go   to the account repo and now in here you know this  must be an async so this can be simplified we can   remove this the same applies to this one can  also remove that because we' added a name space   already now from this login the first thing that  we're going to do here is you know we are going   to when the model or the payload comes in which  comprise of the email and the password you're   going to get from the database that's the user  manager and I'll check if that email is found if   the email of the ID is found then we're going to  check the password does it correspond to what it   has in the database if yes then instead of using  a signning manager we going to use a cookie we're   going to use our um Json web token instead so  we can generate the token and I return it to the   user okay so this what we're going to do first  let's have this method in here very simple one maybe what this method I have created we can  optimize it I believe you canot you can do that   okay but for now we're talking about optimization  here you want to focus on the the concept okay so   here that's what we're doing if this Modo is  null then return the token here is going to be   null and return login container is empty I'm not  sure this is going to be empty because when to   use consume this in the client then we're going to  use the data annotation validator to validate it   before it get the API is very important so maybe  you can also check it as well and now in case it   is not null we want to get the email so if it is  not found then tell the person is are not found   because email is not in our system we can't find  your the information and if it is found then we   want to check check password so we're going to  check the user current user which has been found   and the password the current password it returns  a bullan expression here so is it true or false if   it is false it means your password is not correct  tell the person invalid email or password it's   very risky to tell a person that invalid password  it tells the person that one the email is working   well so the person is not the actual person then  you are doomed isn't it you going to try as much   as possible to get it authenticated so tell the  person either your email or your password is   invalid okay this is my suggestion you can turn  it any way around that you want if it is not or   if it is the same then you want to get the RO from  the user so get Ro okay from the user and now here   it's going to get a whole lot this R here is in  the pral form so we have to since here we want   to assign only a single row we can use first  for to get the first row and here we want to   prepare this us sess for the token generation so  you're passing the ID the name the email and the   to the row this is just the parameter that I need  for my generation token these are the claims I'm   going to be using you can decide to skip the row  you can decide to add you can decide to use only   one property in there to handle for your claim  but for now you want to maintain the three so   I'll teach you how to add row as because we've  done that in the configuration so you have to   also use the row in here then call this method  this method has to return a token as a string   then return this login response which takes in  the parameter of flag token type here and on the   message okay so let's create this method and this  method is going to generate the token for us it's   very simple just about 15 lines of code and then  we are done so you can even optimize this to give   you maybe five or six yeah I try you know you can  do that so generate token in here and now you can   see we are using the system get a security key  from the configuration file that we use you know   we this config get credentials so you're using  this SEC key here extract credential from using   this algorithm h mark sha 256 with a new feature  of net8 we can use 384 512 um and Etc okay but   for now let's maintain 2 56 let's prepare the  claims you know we have the ID you don't need   to convert to two string because you know ID set  to string already so you know here it is a string   I believe this is string so we can specify in a  string yes a string so there's no need for this   we have the name we have the email we have the  row and that's fine and here we want to write   a token so to write a token we need to specify  the isy the audience the claims the expir date   is one day for now you're not adding Auto refresh  that's a refresh token maybe if you want to add as   well let me know I believe you can do that because  I've made a video on how to implement this refresh   token system I leave at the description but if  you want us to implement a ref token based on   this identity type let me know also and maybe I  have a separate video than on that too then we   have this signing credential that is a credential  that we have created here you know this was able   to obtain because we use this SEC key and you  use an algorithm to encrypt it and we have it   set as credential then to write token you have  to call this method to write this token to the   Handler and that's going to return as a string  format because the return type here it is for   string take note so we get it right here and  I return that's all that we are doing very   simple let's go to the controller and add an end  point to get it the token and then display it for us so inside our controller it's the  same thing that we are doing just that   here since they are all HTTP post we need  to specify a different route for that and   this is login so call this login account  passing this login dto and I return the   response very simple and easy one so here  let's run again and see what we're going to have so in here we've registered already do you  remember that so now let's go in there and log   and see if our account is going to be created  now this is an admin this is the first one so   this this is an admin so if I say that user at one  123 click on execute and I'll take note of this   let's see what we're going to have you're going  to have a token yes I'm sure I'm going to have it   yeah that's fine this our token so let's grab this  this our token okay now if I return as user going   to have the token but to check this well let's go  to the controller and I'm trying to attribute here   with authorized so I'm going to have two methods  of the same type I'm going to overwrite this um   solution weather forecast controller now here  let me just overwrite this I have this one and   the right here is an admin and the row here is  an admin so it mean only admin can have access   to this it's return a range of 1 to 10 now I want  to return the same thing to the user meaning only   users can also call this method I want to show  you that the r authorization is also working after   we've authenticated the user so check note check  note take note don't worry don't mind me okay so   we have this auth attribution and the RO here is  to user so it mean that users can have access to   this and is taking a range of one up to five this  one up to 10 okay normally the admin has bigger   one than the user okay so now you have this let's  save this and now let's see so if I open this get   refreshed you see you have this key alongside  with the any if I click on this without inicated   let's see what happen I'm going to have 41 click  on this 401 it means you're not authorized same   applies to the user try this out execute it the  same now let's log in as an admin and try to see   if you log in as an admin execute this going to  have it correctly done but for user going to have   forbidden 43 because you're not authorized to  have access to the user let's try that so here   we going to say user at one two 3 Let's execute  this you have a token grab this token make sure   you not add the double quote copy this now go  to this section authorize passing beer space   I hope you get it click on authorize authoriz oh  that's fine it is done now now let's go in there   and check it up and see so if I on admin 1 to 10  execute this you can see I have it over here 1 to   10 now if I right click on this and go to inspect  element you can see it has added the header where   here has an authorization and that's a bar key  here take note take note not take note Network   tab click on the same execute and I have an admin  um line here check it out we have an authorization   set over here and that's the token that we have  just added this has a lifetime of one day is   24 hours okay so maybe one day after one day it  gets your Spire then you yourself implement the   refresh token thank you okay so this working but  let's try to execute the class section and see so   the user this for admin is working let's try the  user try this up yeah 403 it is forbidden right   so this is forbidden now um you see that's over  here 43 me for winning now to do this we have to   also log in as user so if it was user one then  execute this we have our token this is a user   token and I this token if you try to log in as  admin or get the the API admin you're going to   still have a forbidden because it's only users who  can have that log out and I pass in the same beer   past this and authorize that close it up and now  let's go in there first of all we don't want to   pass this admin so let's hit on it and see who we  have C 43 for reading you are not required to do   that only only users can do that please that is  what is telling you so click on this user click   on execute and must have 125 one 125 and that  is it so we able to achieve ad using identity   manager and able to use thisw authentication  to authorize and authenticate users Bas on an   API request thank you for watching this video I  believe it is clear the sub of this will be at the   tab so check the video description if you want to  also buy us coffee to support this Channel or this   video why I'll be glad to receive it thank you in  advance of doing that and if you're interested in   learning all these task please I have one onone  coaching session so check the description email   there can just write me through that thank  you for watching and I'm going to catch you up
Info
Channel: Netcode-Hub
Views: 3,847
Rating: undefined out of 5
Keywords: .NET 8, Web API, Custom JWT, Authentication, Authorization, Identity Manager, Secure APIs, Programming Tutorial, AspNet Core, API Security, Software Development, Backend Development, Identity Authentication, DotNet, Development, WebAPI, JWT, IdentityManager, SecureAPIs, AspNetCore, Programming, Tutorial, Security, Coding, .NET Development
Id: owk9faapaBs
Channel Id: undefined
Length: 64min 45sec (3885 seconds)
Published: Thu Dec 07 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.