JWT tokens, Refresh tokens and role management in dot net 6 API | Signup & login in dot net 6 api

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there everyone it's ravindra devrani and I have come back with another video I hope you guys are doing well if you find this video helpful then please hit that like button and today we will learn about authorization in dot net core rest apis how to secure our web apis and how to create role-based resources and how to create refresh tokens for longer login sessions and we will also see that how registration and change change password functionality Works in asp.net core identity let's see how authentication works so it is how an authentication request response look like client making HTTP request and he passes login credentials and in return he gets the access token now client passes that access token to the server and gets the protected resource in the response but there is a limitation with access tokens they generally created with sorter validity so that security can be maintained and in case an attacker gets your access token then he can access your data and you don't want to give this privilege for longer period of time so we create a sorter validity for Access tokens now what happens if our access token expires generally we have to login again but we can avoid this situation with the help of refresh tokens and it is how a refresh token request look like we make an HTTP request and pass our login credentials and get access tokens and refresh tokens in the response and what if our response sorry refresh tokens expires we make a request for new access token and now we don't need login credentials again we pass refresh token and in response we get the new new access token with longer validity now you might be wondering that how these access tokens are secure now attacker can use our website for longer period of time if he has this access token but it's not the case now Now situation is in your hand if you suspect that attacker have your authentication token then you can call a revoke method which will destroy your access token information that is stored in your database so it is how authentication works now let's understand these concepts with the help of code so let's start with creating a new project so click here create a new project and then select a template and from here we can select asp.net core web apis so click on next and let's rename it YT movie apis Okay click on next and here it is asking to select a framework so we will use the latest framework which is dotnet 6.0 and and here let's uncheck this enable open API support we don't need this okay let's create let's click on create okay our project has created now and let's try to run it in browser okay so our project is working fine here you can see that we are getting some data okay now let's do some work okay what to do first let's create a connection string first so here click on app setting dot Json and here let's write a connection string so connection strings corn data source equals to Dot initial Theta log equals to YT movie DB and it's not a comma it's a semicolon and here Integrated Security equals to true it means that we don't need any password and username for Authentication okay I hope it is fine data source initial catalog and Integrated Security now let's create it and create a folder here add new folder and name is two models and inside this folder add two more folders one is domain here we will Define our database classes and one will be dto here we will Define our dto classes so it will be dto and let's create a class here which will be database context class database context dot CS but first we need to add some packages so click here in tools select nuget package manager and manage package and package manager for solution so here okay we need some packages like this Microsoft dot Entity framework code.sql server so okay so let's install it okay and it will take a while so please be patient or skip this portion of video it is much easier to escape rather than weight except okay let's add another package which is dot tools Microsoft dot Entity framework code.tools and it is used for our nougat package manager commands if you want to enable it then you are not able to run your nuget package manager commands okay so make sure to install it okay and click here on install okay let's add another package which is microsoft.asp.net core dot identity and here let's click on install okay and add one more package which is Entity framework core so install this package also okay and let's install one last package which is microsoft.asp.net core dot authentication dot jwdb error so install this package okay and it is our last package okay accept it and just wait for a while okay now all the packages has installed so let's close this tab and now move to the DB context class and let's add one more class here which will be application user application user and let's inherit identity user here press Ctrl Dot and select using Microsoft dot asp.net core dot identity and add type p r o p double tap and it is a shortcut for creating a property let's create a property with name sorry public string name okay and now here identity DB context and it will be our database context so here right CTO sorry c t o r and it will create a Constructor here so right here DB context options TV context options okay and database context options and right here base options okay it's fine now and what it is saying let's see quick actions and refactoring extract Base Class okay here is a error it will be our application user application user okay now it's fine okay we are done here so let's close it and now now open app setting dot Json and here add some lines which will be related to JWT so here is our valid audience it is a URL of our client application and we are assuming that we are running that application on localhost 4200 and you can change it according to your need and it is the URL of our valid issuer and it is the URL of our application 7010 Port so 7010 and you can check it from here from your browser also which Port you are using or which URL you are using in your project so just copy this line and paste it here okay okay let's close this tab and now we are going to add some classes so first we will add this class which will be user roles and here Define these constants here admin equals to admin and user equals to user okay now add some more classes and here at this class which will be our token info class we will store the information related to token here so it will be token info dot CS okay so here we will have ID and a string user name and refresh token and refresh token expiry foreign username refresh token and refresh token expiry and it will be a date time date time okay it's fine now and add one more class here and just name it token response dot CS prop a string token a string here date time valid 2. okay okay let's close it also and I think we have created all our models if we need some more we will create them in future so let's create a one more folder here which will be our repository folder so here repo Z Taurus and here had two more holders which will be abstract and domain domain and let's leave this folder as it is for now and move to the r token no database context class and here write public DB set token info we will add this class into database so token info and token info get get set okay now let's add these things into our database so here click on package manager console and type here add migration in it and it is giving an error unable to create an object of database context so let's see what it might be okay let's open this okay I see now what might be the error and it is a big mistake I haven't configured my program.cs class so let's configure it so here right here Builder dot services Builder Dot services it will be our database context class so it will be our database context and here it will also be our database context and press Ctrl Dot and here using Microsoft dot Entity framework core okay fine and here Builder Dot configuration Dot get connection string and our connection string was c o double n con okay we are fine till now let's add some more lines and here these are the configuration we needed in our project so here okay let's add some more and here okay so all of these configuration we are needed in our project so it is for our Entity Framework and here we are defining that which database we are going to use we are going to use SQL Server so here we are defining our connection string and it is for our custom identity which we are using in our project and it is our custom identity user class which we have created recently so we are mapping it to Identity rule and here we are adding some information about authenticator authentication and we are using JWT authentication and we are configuring it here and here we are adding some JWT b error configuration so here we have defined some options if token equals to True require https metadata equals to false token validation parameters which will be validate issuer and validate audience validate valid audience valid issuer and issuer sign in key okay so here now let's try to run our migration command so here open tools SQL Server no not SQL Server you get package manager package manager console and here add migration init okay it is fine now and let's write update database okay it is I think it is working fine okay let's wait and see okay and all of these things has added to our database so let's close this tab and let's move to the program dot CS tab right now and here add one more line which will be app Dot use Authentication okay and add it before the use authorization make sure and here add this line we are enabling cause properties so here these are the options and origin okay okay we are fine now okay and we are done here in program.cs file so let's close it and let's close it also okay now okay let's add some more classes we need for our login and registration so here add registration model already stress and model a string username restraint password username email and password okay and let's add some validation here so it will be required and all of these field will be required so okay now let's add one more class which will be our login model so here it will be login model and we do not need email here okay and let's rename this file login model.cs okay and add one more class which will be status dot CS and it will have two properties first one will be message and another one will be a status code public and status code okay okay now here let's create a service file which will be an interface and let's rename it to Ken I token service and rename it open service let's add some methods here but before we need to add some more classes okay I think we have added those glasses token response okay fine token response get token and I enumerable claim claim a string get refresh token and claim principle get principle from expired token and here will be string token okay now implement this interface in the domain folder so we will add another class which will be oh what was the previous one token service so it will be token service okay and we will implement this interface here I token service and right click here click action and different refactoring and Implement interface okay and now we will add some functionality here one by one okay let's define Constructor first so type CTO R double tab and here write private read only I configuration underscore configuration and here okay that's fine now it is giving lot of Auto suggestions which are very useful okay that is fine now let's define this method okay and I already have written the code so I am just pasting it here here we are accessing signing key and we are accessing this key from our app setting.json file which is hit Secret and here we are creating a token and we are also getting these things from app setting.json file we have declared here valid audience and valid is your okay and it is our expiry date of that token and here claim are coming from the user end and signing credentials and we are creating signing credential with the help of this algorithm okay you don't need to worry about code I will provide you code in the description box so please do not worry about that okay and here it is our token string and we are returning that token string to our user okay fine okay let's add this method and here here we are getting token validation parameter and we are setting these properties statically a validate audience will be false whether it is issuer will be false if you are signing create true and signing key will be get from our configuration file and lifetime equal to false okay and add one more line and Define our token Handler okay and Define one variable here security token security token and we will get it from the method with the help of out parameter we will pass it as an out parameter okay and here we are passing this security token and it is let's change it to security token where principle equals to token Handler dot validate token token we are passing three parameter token token validation parameter which is defined here and security token okay so JWT security tokens equal to security tokens at JWT security token okay and add one more line if security token equals to null JWT security token dot header dot ALG equals security algorithm etc etc then it will throw this exception invalid token and now we will return or principle okay [Music] okay and this method is completed now now we will implement this method get refresh token and we will generate a random string here so here we are generating a random number as a byte and now here we are creating a random base64 string and returning to our user so we have implemented all these methods and our token service controller is completed okay okay now here open program dot CS file and here add these services to di container so Builder dot service Dot at transient I and what was the name of that service I token service I tooken service comma token service sorry not iot token service it is token service press Ctrl Dot and enter okay it's fine now okay now let's create a controller with the name of token controller so here add new controller and change it to the API controller empty and its name will be token controller token controller okay now here at this line controller slash action okay now we are good to go and Define a Constructor here and private read only database context CTX equals and private read only database sorry not database I tooken and what was the name of our service I token service I token service underscore CTX and okay so defined here database context CTX comma I token service here this dot CTX equals to CTX and this dot service equals to service okay now let's define some method here and it will be HTTP post method okay but first create a model grass and it will be our refresh token request dot CS and here Define access token and refresh tokens refresh token okay and now add a controller method here which will be refresh public I action result refresh and preface token request refresh token request it is the class we have created recently okay okay fine okay let's rename it token API model and let's check this code here we are checking that our token API model is null or not if it is null then we will return a bad request with the with the message invalid client request so here we are getting access token from the token API sorry from the user end and here let's change it to service okay and ctx2 CTX okay and token service to service U Dot username call to username and here user Dot refresh token expiry and it is our refresh token model okay fine so here we are getting access token and refresh token from the user and and here we are getting username from principle.identity.name and here we are getting the user info from the database and we have created that class token info so that we can store the information related to the Token of that particular user so we are fetching that information here and if user is null refresh token does not equal to reference token it means that he is passing different refresh token and that refresh token must not be expired okay then it will return invalid grind request otherwise it will assign a new access token which we will get from our service and new refresh token it will get also from our service and here assign user dot refresh token equal to new refresh token and now save changes to the database and basically we are saving this token info table into the database okay fine and now we are clear about that method now we will create one more method which will be revoke and revoke revoke removes your token from the database if you want to remove that token from the database you can use the revoke method the work is use for removing token entry okay so here public I action result revoke here it will be HTTP post method and it will be an authorized okay and it is the code for revoke so here CTX so here we are fetching username from the user.identity.name and here we are finding the record from the token info table on the basis of that username so here U dot username I have done a spelling mistake I forgot to write R here okay and if user is null then bad request otherwise set refresh token to the null and save changes fine and here just add try catch block so here try catch exception EX and return bad request or let's return let's remain it bad request okay it is our revoke method okay now we will create our authentication controller so here add new controller and it will be foreign API controller empty and it will be our authorization controller and let's define the Constructor here private read only database context context and right here also okay now this dot context equals to context okay and add a line here I'll add a line here which will be accent and let's define a new method here public i x and async task i x and result login and here login model will be passed okay now find a user where user equals to a weight and let's define some more things here so these are the methods sorry not methods Services which we are going to inject in this controller and here put this thing here also user manager comma role manager and I token service okay and this Dot user manager equals to user manager English dot role manager equals to role manager and this Dot token service token service equals to let's remove its underscore from here to come service okay Constructor is completed here so let's move to the login method await user user manager dot find by name async and here we will pass our model dot username so here we are getting the information of user from the user manager service okay let's create one more class here which will be login response and type here login response dot CS and it will be inherit status class okay it is our login response class here we will Define token refresh token expiry date name and username so let's close this tab and move here okay let's check a condition if user does not equals to null and user manager sorry user manager dot check password async it is essing Method so we will write a wait here I think model let's see what it is asking to us it is asking that application user and password so user comma model dot password okay so if user equals to null okay if user equals to null does not equal signal and check password does not sorry it means that your password is matching to the database then you are logged into the database it is the condition for logging in to the database so now we will find role of the user with user manager get rolexing method and here we are creating a claim list so our claim will be name and we store username into this name claim and press Ctrl Dot and let's resolve this okay fine and it is a new claim for jwd token which is jti and here we are passing a random GUI string into it okay okay let's add all these claims so we will find all the rows and we will add them into our claim so let's find our token where token equals to token service dot get token and it is asking for a claim so we will pass auth claims here and where refresh token equals to token service Dot get refresh token okay and it is not asking any parameter so we are good to go okay now find out open into database so token info equals to context context dot token info DOT first or default a DOT username double equals to user Dot username okay if token info does not equals to null if token info doesn't equals to null sorry means equals to null where info where info equals to new token sorry token info okay what is the name of our token info okay fine so token info equals to username username equals to user dot username and here let's see refresh token equals to refresh token refresh token and one more thing token expiry equals to date time dot now Dot add days let's add seven days okay and otherwise we will modify it and here token info otherwise token in four dot refresh token equals to refresh token and token info dot refresh token inquiry equals to this this okay let's format this document and here context dot save changes okay let's add a try cash block here catch exception EX return bad request and here pass exception Dot message okay and now return this login response object name equal to user dot name username token refresh token expiry date and status code will be 1 and message message will be logged in okay okay now we will write a login field condition login field condition here otherwise okay equal to new login response status 0 message invalid username or password token blank and expiry null okay so it is our login method and it will be HTTP post like that okay fine now let's write registration method public first it will also be an HTTP post method here public I think task I X and result here register sorry registration from body registration model model okay if model state is not valid then written from here where status equal to new status and type here status Dot status code equals to zero status Dot message equal to please pass all the required fields okay fine and return okay fine okay now first we will find that user exist or not check if user exists so where user exists equal to user manager Dot user sorry find user find by name async and here user Dot sorry it is not user it is model dot username if user does not exists we will return from here okay it will be await okay sorry it is not a Boolean value if user user exists equals to null then copy all these feeds and let's pass invalid username and it's fine okay now we have checked this condition okay now create a new application user where user equal to new application user so username equals to model dot user name equals to model Dot let's leave it blank for now and security a stamp equals to goit Dot new guido2 string and email equals to model Dot email and it will be our last and we haven't defined it inside our registration model so let's define it and where is our registration model it is here okay let's define name also here so it will be our name fine name equals to model dot name and okay now we will create a user here so where result equals to await and user manager dot create hashing and let's see what it is asking it is asking pass me a user with the type of application user and please pass me password also so let's pass password also okay now check if result is not succeeded 10. written from here okay and let's return from here let's type a message user creation failed and we are passing okay from everywhere and I think it should be okay we don't want any kind of error messages in the client application and it is my preference if you want to pass Five double zero internal server you can pass also it from here it's all your choice now okay now let's add roles here and here here first we are checking that row like this in database or not if it does not exist in database then we will create a new rule otherwise we will move forward and now here we are checking that that user has that role or not if user does not have that role we will add that role in to the user okay and it's not not a complex line so it will be okay okay now after all of this we will return and 4K status from here it means that our registration has been successfully completed user success fully registered okay guys and if you want to register for admin for admin use user roles dot admin okay use user role dot admin instead of user role dot rules so replace all the user roles dot roles to the admin for admin registration okay I think we are good to go okay now let's run our application and here are some errors and it is expecting something here okay it is expecting curly braces here and a semicolon also so let's see everything is fine or not okay everything is fine so let's run this project okay and no error so far so everything is working fine okay let's close it for now because we need to add one more functionality to it which is change password okay okay but first we need to add a dto class for it so we will create uh change password model okay so here string foreign sorry current password and it will be our new password and confirm new password okay and let's add require field here so required required required and required and let's add one more field here which will be our username so here username and now we are good to go let's write a method for change password Here okay so it will be our HTTP post method public async IX and result sorry it will be wrapped up inside task public I action result change password change password model okay so here is a spelling mistake Okay so now we are fine pass here model okay so where status equals to new status and let's check the validation if model state is not valid then we will return from here written okay and status Dot code equals to zero status Dot message equal to please pass all the fields all the valid field and let's modify this class here we will add one more attribute which will be compare and it will be compared to the new password so new password and confirm new password should be same it's not same same okay let's return model from here okay status okay now let's find the user where user equals to user manager Dot find user by name find name find by name async so it will be how it and here we will pass model dot username okay and if user is null then we will return from here and let's copy this code and paste it here invalid username okay now we will check current password so where if a weight user manager dot check password I think user comma model dot password model dot current password if we do not match our current password then we will return from here with a status code 0. so invalid password invalid current password okay now we will change our password Here so here okay where result equals to await user manager Dot change password hashing and it is asking for user then current password model dot current password and model Dot new password okay if result dot succeeded not succeeded then return an error message otherwise return OK result failed to change password and here return a status code 1 and here password has changed success fully okay now we are good to go and let's check it that it is working fine or not so we will run our application okay guys everything is fine so let's close it for now and register an admin okay so here just copy this method and paste it here and where it is it is here let's rename it to register admin okay and here admin and let's change it to admin admin okay now we will register an admin here after that we will comment this code after registering admin we will comment this code because I want only I want only one admin in this application okay so let's try to register admin so let's see okay we need name username email and password so let's run our application and meanwhile open the postman open the postman app so here inside this Postman we will test our apis so paste this URL here and now right here API slash name of our controller which is authorization controller and authorization slash register admin okay let's pass body here and it will be Json format so name let's John Doe and username let's name it to Zone sorry let's name it to ravindra and username r-a-v-i-n-d-r-a let's try to add username as admin so admin will be our username email will be red XYZ dot com and password will be admin upgrade one two three four five hash or let's just leave it to admin at the red one two three okay so it is saying that four zero four not found so its name is registration admin okay method not allowed okay let's see why it is not allowed request was made of resource using a request method not supported by that resource okay okay here we need to change post okay let's see what happened so it is saying invalid username so let's check it in our Visual Studio code and here we have to change this condition user exist does not equal to null it means user should not be existed in your database so let's change it here also user exist does not equal to null and let's check it again okay and let's check it again okay guys it is saying that successfully registered so let's close it for now and comment this admin registration method we do not need it anymore okay now let's comment it and now register our user then we will try to login okay and let's move to the postman um URL will be slash registration and it will be zondo and username will be j o h n capital j and password email will be shown at the rate XYZ and password will be is on at the red one two three okay so our password must be six character long and it must have one capital letter and at least one capital letter and one small letter one one special character and one digit that's it so let's try to add our user okay guys here it is a success message so now let's try to login and here we will pass only username and okay let's open a new tab and here it will be your post request and here our body which will be raw and we will pass this and format data here so our username is admin and password equals to let let's pass wrong password so okay let's hit that API and here one or more validation error here password field is required okay so let's see our login method go to the definition and here username and password and here username okay invalid username or password and let's try to pass our valid username sorry valid password so valid password was admin android123 so let's check it okay we have successfully logged in and it is our token and here it is our refresh token and it is our expiry date and it is our name username admin etc etc okay fine now let's stop it for now and let's create two more methods sorry two more controllers one will be our okay it will be or admin controller okay and another will be okay just name it it will be our API controller and let's name it to protected controller okay action okay and public IX and result get data and let's write an authorized attribute here authorize so this controller will be authorized get data and here written okay data from protected controller okay and here action admin controller and it will also be authorized and here we will Define rules and it will be assigned to admin only so only admin can access this controller okay now let's check these controllers okay so here let's open one another tab and here protected slash get data and let's try to access this thing and it is saying that 401 on earth right okay it means that you are not authorized to access this controller okay and here now let's try to login again with the user joh and John and it will be shown at the rate one two three so let's try to login okay now we are successfully logged in so let's copy this token and copy copy it and now let's pass it here inside the headers sorry inside the authorization and it will be our Bearer token and let's paste it here okay now try to access this resource and yes we are getting data which is data from protected controller now let's try to access admin controller and here it is saying that four zero three forbidden it means that you are an authenticated user but you are not authorized to access that admin controller only admin can access that controller so let's try to log in with admin credentials so here admin and password will be admin at the red one two three so here let's copy this thing and here paste it here and let's try to access this thing it is I think it is not locked in yet okay let's try to log in again so here username admin and password admin at the rate one two three so here let's copy it and here paste it here and it is asked it is telling again four zero three four be done okay we will find the error don't worry okay let's debug here and now let's check it and here we are getting our user info so here and here are our rules and rules equals to admin k and here is small a so let's change it to Capital a that was the error okay let's check it again in the postman so here let's try to access this resource and now it is saying that data from admin controller so now let's try to check our one more method which will be change password model method and here authorization change password it will be a post method and here we will pass Json data and here username will be admin current password current password is admin at thread one two three new password new password will be admin at red one two three four five has and confirm new password equals to admin address one two three four five hash so let's try to check it and let's see what happens and here it is saying succeeded equals to true but we won't believe in that message and we will check with ourself okay and now let's try to okay let's remove that breakpoint and it is saying that invalid username or password so here one two three four five hash okay and let's see what happens okay and here we are successfully logged in okay now let's check our refresh tokens so let's close these tabs we don't need these and now here it will be our token controller okay let's open our token controller and here we have a refresh method and let's see what we have to pass inside that method we have to pass access token and refresh token so let's select Json and here pass access token and refresh token okay and we will pass these values from here okay it is our access token and it is our refresh token oh so let's copy it and here paste it okay and it will be a post method so it is saying that invalid client request okay where is our token controller okay I think model is null that's why it is saying that invalid client request let's see why is model null access token and refresh token okay if user is null and here it is not finding any user in our database okay so it means that problem is in our login method okay and here is a huge mistake I haven't added in sorry context Dot token info dot add token info not open info it will be info okay now let's check it again and we will login again let's try to login again okay and now let's pass this value here and first this value here okay and here we are getting access token and refresh token Okay so r211 controller is also working fine okay now let's try to publish these things into our local IIs server so we will publish them into our IIs server so let's close it for now and to deploy your application on local is server you have to enable some features so type here control panel and programs and features then click here on turn Windows feature on or off so click here then click on internet Information Services and when you click on it then make sure that this IIs Management console must be checked and then click on OK and it will enable your features so after enabling your features you have to download asp.net core 6.0 runtime Windows hosting bundle installer I will put that link in the description box so do not worry about that okay and after that move to the visual studio and here right click on your project then click on publish and we are going to select folder and here okay let's assume that we are going to publish our file inside the published folder and we will create a folder here which will be YT movie API published and let's copy this path and it will automatically create this folder if it does not exist in your computer so do not worry about it okay then click on finish then close okay now it is ready to publish so let's publish it so our files have been published okay and we can see that they are published here so copy this location and right here init manager inet MGR and click on IIs manager okay here right click here on the sites folder and add new website and let's name it YT movie apis and it is a physical path that we have copied earlier and let's change the port 88 and please guys do not use this port 87 otherwise you will get a Port 88 Okay now click here on application pools and here YT movie apis click on advanced settings and change its identity to local system then click ok now here manage website and browse and it is saying that this localhost page cannot be found so here type weather forecast and our website is working perfectly but we need to give permission or database so let's close it for now now we don't need it and open the SQL Server and inside the SQL Server click on security tab click on logins and here anti-authority system here in user mapping and select your database it is our database YT movie DB and here click on this dot dot dot icon and click on browse and let's give it a permission of DB owner okay and here also select DB owner and now we are good we have given permission to our database so here let's test it in our Postman and it is our login API endpoint so let's try to login okay guys that's it for now and if you find this video helpful then please hit that like button it really encouraged me to create more content for you guys so see you in next video
Info
Channel: Ravindra Devrani
Views: 8,582
Rating: undefined out of 5
Keywords: role base authentication in dot net core api, refresh tokens in dot net core, jwt tokens in dot net core, login and registration in dot net 6 apis, login and registration in dot net core apis, role base authorization in dot net 6 api, change password in dot net 6 apis
Id: g2WHURQObzQ
Channel Id: undefined
Length: 109min 40sec (6580 seconds)
Published: Sat Oct 15 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.