Jwt Authentication in blazor | Role based authorization in blazor webassembly

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there everyone it's ravindra here back with another video in this video we are going to learn how to secure our Blazer webassembly app and how to display pages on the basis of role because certain pages needs to be displayed only to certain person suppose some of the links you only want to show to the admin and some links are only to be shown to the manager and some links are available for everyone who is authenticated and even some links are available to everyone even it is not authenticated for that we are going to use Json web token that we will receive from the API side after logging into the DAT API so let's get started without any delay and actually we are not going to cover API tutorial here because I have already created it so you need to do one thing here go to YouTube into my channel and here in this playlist you can find you can access this playlist dotnet 6 Plus project and solutions here you will get this video JWT tokens refresh tokens and role management hint.net 6 API when we click here so you will get a complete tutorial how to create the JWT token based apis with rule management and all and you will also learn how to publish those apis in your local server so when you publish those apis here you can easily access them so I have deployed here in localhost apis sorry localhost 88 slash weather forecast so here I already have published that web apis so we do not need to run that application again and again for using the web apis so you should do this same and I already have explained everything in this tutorial if you want to watch it you can watch it either if you do not want to use it or watch it and you have pretty much idea about how to create apis and how to use them then you can simply go here in the source code in the description section and you can find the source code here and when we click here it will go to my GitHub profile and from here you can download this code either you can push the request or you can download directly the zip folder after using the zip folder extract it and open that application and remove the migration file do not forget to remove the migration file actually I'll let me show you where you will find those migration files so click here and here inside the migration folder you delete these mic these all of these files then create your own own migrations by using commands like add migration slash name of migration after that use update database command and it will create a database for you now you are good to go with that project so after using that project if you are not following the video then let me show you one more thing when you go there authorization controller and you will find a method which I have commented so this method is commented uncomment it it is used for creating a admin user because we do not want to give right to create admin from the outside so I have created this method created admin once and I have commented this so you do the same uncomment this method and just hit that method with Postman and it will create pass some values and it will create a admin user for you and then uncomment it so this method will only be used for creating admin and for creating for registering user use this method keep in mind this method is used for creating admin nothing all so actually I have covered all of this thing in video if you do not have time to watch that video that's why I am showing you few things so keep these things in my mind or sorry your mind and you can even watch this video it's totally up to you so after using after downloading that project and deploying that project to your local IIs server which is here IIs and you need to publish it there I have created a separate video for this in my channel and also this video covers the publish to the IIs somewhere here in the video at the end you can see how to publish this particular project in the IIs web server or you can find this video it is a separate video deploy deployment of dotnet6 app to the local is server and after that I am just showing you here I have deployed that project it is the project and when I click here browse so and if I write here weather forecast okay so it is the URL of that project and if you do not want to publish that project it's totally up to you you can run it separately but you have you always have to keep on running that project that is the problem okay so now I guess you have downloaded the project and deployed it even in your IIs after doing that what you have to do click on the visual studio now create a new project and search here Blazer so we need to select this Blazer webassembly app not this Blazer server app both are the separate things actually Blazer webassembly app is totally client-side but Blazer server app gives you the option to create both client-side and server side in a single application in the case of Blazer web assembly it will also give you the opportunity to create a separate project for create add a new project of type web apis but actually there are two projects not this single one when it comes to the deployment you have to deploy both projects in different different server so these are two project in this web assembly app if you use if you use them then they need to be deployed separately actually they are not the one so click here the next and let's change the location let's name it Blazer auth Blazer JWT auth Okay click on next now if you click here asp.net core hosted it will create three projects for you first one will be the name of your application that was Blazer JWT auth so first project will be JWT auth dot client next project will be JWT auth.server which is a type of web API project here we will you will create a web API and the third one will be your application name Dot shared and that is a class Library project that will be shared by both client and the server application so we are not going to do that because we already have created our apis so we do not need to create those projects so keep uncheck this option and we also do not want Progressive web application and this option should not be ticked so only tick share click here in the configure for https that's it and we do not need any authentication type also so let's create a new application background so it is our default application let's run it so it is how it looks like you already have familiar with it I'm guessing that you have created separate several projects in it and you are the new user here because at this point you are looking for authentication it means you have created a project without Authentication and now what we need to do we need to create ah sorry not create we need to install some packages either you can install it from here and go here in browse and type this esp.net core asp.net code dot component Dot webassembly dot Authentication and select this project and install it it is a one way of doing it and I find it little bit time taking so I do not prefer it I directly like to install them from here from the command line install package and the name of the package and it's done so it is so much quicker than that now we need a second package install package Blazer dot local storage and I'm telling you why we need this package because we want to use local storage in our application for storing the token and Blazer vessim or Blazer work assembly do not give you a direct do not give any direct functionality by which you can use the local storage for that for using the local storage we need a third party third party application or third party package so that we can use the functionality of locally storage and you can easily use local storage in the JavaScript or any JavaScript framework but it's not the case here in the Blazer you need a third party application and I do not find it very useful so actually it is what it is so we can't complain about it so install this package after installing these packages go there and close it for now click here Builder dot service Services dot add authorization code do not forget to add this service here and one more service that is something add Blazer local storage okay so now we can use the local sorry Blazer local storage as a service in our whole project so close it for now now open this app dot Razer file sorry not this open this import dot Razer file and here we are going to use this Microsoft dot asp.net core dot components dot authorization now close it for now and open this input sorry not this import this one app.weiser and now we need to change it authorize route View and sorry so inside that we can write this thing authorizing so when we are authorizing it will display a message we are authorizing the user something like that okay so let's close it for now again so here first of all let's create a folder utility and we need a JWT passer for parsing or JWT token so let's create that JWT parser and let's create this class as static class and here we need these two methods so this method will pass claims from JWT uh actually do not worry about that I will put the source code put the link of the source code in the description box so you can copy it from there and you can originally found it somewhere in internet and it was somewhere in Steve Sanderson project so thanks for him for creating these methods so now we have our JWT parser so we do not need to worry about that let's close it and now we need a custom auth class at let's create a folder for that auth provider and here create a class or provider dot CS now we need to create a Constructor here for that type ctor double tap now we need few Services here and one will be HTTP client it is needed for making HTTP calls and local sorry it is something like I local storage service local storage okay so click here and press Ctrl Dot and click here create and assign field http and do the same here create and assign field local storage okay now we need to create Anonymous user that is by default it means that user is not authenticated so right here private read only authentication is straight anonymous okay and let's assign a value to it here new authentication State new claims principle press control dot here new claims principle and inside that new claims High identity so it is the by default value of this Anonymous user and it means it is not user is not logged in yet so now what we need to do we need to inherit this class from Authentication state provider now we need to implement some methods here first one will be public override and pressing async task get authentication state async so just add here async now it is fine so let's type here some lines first we need to fetch token so token will be fetched from the local storage and okay so let's just change this name to this to this and here also now we can remove it from sorry remove this okay now we are good so I'm much comfortable with underscore name local storage Dot get item async will be a string type and let us suppose I have stored a token with the key access token I haven't stored it yet but I will store it in future with this name okay so now we have retrieved token so let's see is token if token is empty string dot is null or empty token if token is empty then we will return Anonymous user it means we are not logged in okay now here it means we are getting token so we need to set default header that is actually we need to set b error token into the header for every request and it is a kind of Interceptor in the angular so here just write http dot default request headers dot authorization equals to new Authentication header value and just remove it press Ctrl Dot Okay so remove it from here and add it here using in this way it looks much cleaner now right here new authentication header value so let's see what it is asking from us string scheme Bearer comma token be error comma token okay now we have set the header let's return from here return new authentication state new claims principle and here new claims identity and new claims identity okay so inside here what I need to do I need new claims identity and we need a JWT parser here so JWT parser parse claims from JWT here we needed that parser and just pass here the token and type JWT [Music] auth or okay so it is giving me a no overload method for zero and two argument okay actually it is needed here so it must be like this and this new claims identity should be moved here now it's much more readable okay so now we need to implement another method public void notify user Authentication string user name and this method will be used by this actually I forgot to add a line here so add this line here cascading authentication State and wrap up all of the code inside this so that notification method will be used here okay so let's write here where Earth user equals to new claims principle new claims identity and here we need a array new claim claim types dot name username so we are adding the claim here comma and I guess it is needed here comma so here it is asking authentication type JWT auth okay and let's hear JWT auth type jwd auth type now we need another method for log out and actually we need one more line here that is notify authenticated authenticated State change auth state or and we need to create this where hot State equals to task Dot from result new new authenticated state authenticated state and I guess it's a authentication state so authentication state auth user okay it is looking fine so we need another method for log out now so public wide notify user logout notify user log out wait a minute okay so notify user log out what we will do here we will change the auth state North State equals to task Dot from result and now it will be anonymous because we have logged out um we will do the same notify authentication States changed okay so what we need to do we need to resolve this dependency here so click here Builder sorry here Builder dot services dot had scoped and Authentication provider authentication state provider comma which one we have created and we have created auth estate provider press Ctrl Dot sorry it was auth provider so hot provider yeah this one okay now we have resolved the dependencies now the hard part is done okay so what we need to do now now we need to access these apis and for that I need to create these classes this class and this class this class and this class also okay so we will create those classes here and add a folder let's add here models okay first one will be our login login dto okay it will contain string username and password fine let's put some validation here required okay now we are fine r e q u i required okay first one is done now let's create some more classes like the status and here status it will contain integer type status code and a string type message now I need one more class and you can call it login response so here add a new class and let's name it login response first of all it will inherit this status class because we need those two properties that we have defined inside the status class and we need these properties token refresh token expiration name and urm although we are not going to use refresh tokens here and actually we do not need all of these details also but I have already created this API so I do not want to change it so I'm just showing you that we do not need these properties in this project we only need the token so it is our login response so after that we need a services so I will create a folder services and here we will fetch the login service so here create a class and name is Authentication or auth service let's name it Authentication service that's it Okay so let's create here method public I think task login response [Music] and login it will take login dto as a parameter now first thing what we will do we will try to fetch we will try to use the web API here so here what we need here so we need a HTTP service so we can write here private HTTP client HTTP client and I local storage service local storage okay just press Ctrl Dot and create an assigned field foreign field okay so right here fine fine let's add another variable here private read only a string base URL and from where we will get that base URL from here so it is mind base URL you have to change it according to you so keep that thing in mind do not paste the same thing so here assign base URL equals to this fine and I'm removing this character from here now what we need to do we need to wear result or where should I name is login result equals to HTTP client Dot forced async fine here it is asking me to enter the URL so I will enter this URL and sorry not this URL okay and now slash login I guess that's the correct one so where it is it is here slash login okay comma and here it is asking me to http content okay so I cannot directly enter this model here for that Okay so I guess we can do that I'm not sure so we will see it in future okay so let's see what it is asking what it is saying cannot convert from Blazer jwdrs login dtos okay so I was right we cannot do that for using it directly we have to use post as Json async but I guess I find it's hard to track errors from this method so we are going to use post async and we will convert this model into a Json Okay so actually we can use post as Json async now we are fine and we can track the success or unsuccessful API means we are we are hitting this API successfully or not we can track it here like this login result dot is and actually I forget to write here wait a wait so we can write here is success okay now is success status code so we can track it here if we are not getting any success code then we can write here where login where login response or simply response equals to new login response and we can write here response equals to new login response and here status code equals to zero status sorry message equals to server error and we can return from here written response okay so now what we have to do we have to fetch the content of this login result so login response content equals to login result dot content dot read from Json async now here we will we will write a type of data which we are expecting from this this response and that is login response this type of data this login API is returning us okay so now we have converted this Json data into the login response okay so we can simply return this login response okay sorry not right now and here actually we do not need it we can simply written it and we can move these lines okay we can return this login response content at the end but here if login response content doesn't equals to null here what we will do we will add Json sorry locally storage dot set item async and access token login response [Music] login response content dot token and I guess it's a weight also okay content token okay and here what I need I need to add authentication Service hot service comma and press Ctrl Dot create and assign property and what we will do here we will create auth service and change okay it's not property sorry where it is okay so just read here press again create and assign field press Ctrl dot here and okay we have done that hot service just put underscore here and another score here now what we have to do here auth service Dot and here we are not getting uh we are not getting anything so we have to type cast it okay auth provider press Ctrl Dot okay now we can and okay I have done a mistake here it is a Authentication State provider authentication State provider or the state provider change here change here also authentication state provider provider okay change here auth State provider or state provider and other state provider now we are fine and okay so yeah so it will be auth State provider dot notify actually we are not getting it again okay so let's wrap up it inside these two parentheses now let's type here notify user authentication and here login sorry model dot username okay now open this file and and copy this line paste it here now here instead of this token login response content Dot token okay so press Ctrl dot here we are fine and it's HTTP client here okay so that's not a problem so now let's write a logout method so public as sync task log out first of all what we need to do here I'm going to copy this line and okay so this line and somehow I need this line also and here local storage dot remove item async access token first we need to remove that token okay now what we are going to do log out notify user logout okay and here and we will assign null here so remove this and equals to null so it is our log out method so this thing is completed now add interface for it high authentic ation service and let's see press Ctrl Dot generate interface High authentication Service in a new file let's see it can generate as for or not okay so it has generated this file here and it hasn't generated a methods so I think we need to copy these two methods okay so just copy it here and we copy one more thing task log out Okay so we are going to resolve these dependencies here first of all I Authentication service and authentic ation service so let's do one thing here open this thing and if I write here press Ctrl dot using Blazer dot services I authentication Service okay so if I add this line here so it will only limited to this file if I have to use these interfaces again I have to add this this line again so I'm going to add this globally here inside sorry not this this one and I will put this thing here so that we can use them globally okay okay so I guess it works only with razor pages so I just have to add this line here press Ctrl dot okay fine Okay so let's comment this thing here maybe we need it in future okay so that is fine now let's see what we can do now we have created this authentication Service so I guess we need to make and components make a component so okay I have added this I was double checking it okay now we will create uh login component public new yes razor component and it will be our login component okay so we will add a route here page equals to login Okay so here let's create a form for a date form and for that I need something like login dteco and login model equals to new press okay it's not gonna work now in dto if I press here Ctrl Dot sorry press Ctrl Dot using Blazer auth dot models so here we do not have equals to okay so now let's click let's do one more thing here we need a model equals to login model and at the rate and on validate submit for that I need a model so let's name that model equal to async task save our do login okay let's put it here on value Summit now okay if I write here validate data annotation validator okay fine and we need text input text okay but but before that what I need to do div class equals to form sorry row and div class equals to call md6 that will be enough and here edit form do class equals to and it will be form group class equals to no no in sorry input text and class text class equals to form control okay NG bind sorry not a g mind value at the red bind value at the rate login model Dot login model Dot username yeah and it will be like this I guess we are fine okay now what I need here validation message okay four equals to what I need here and login model dot password okay let's copy this guy here and I forget one thing m y 2 it will create a margin from top and bottom okay so here I just need to change password and yeah password and here username and one more thing label for equals to username label just copy this item and paste it here copy password from here and here and here I need my2 just need two divs and one div will display the message and another div will contain the submit button so button type equals to submit plus equals to BTN b t n primary okay type here login and here we will contain a message or message no actually let's create here login response login response equals to new okay so here we will type login [Music] response Dot message okay so here I will write login response Dot message equals to wait and then we will inject the service the login service so here just try to login sorry inject I authentication Service I authentication Service okay I authentication Service and it will be part auth service and one more service we might need navigation manager manager new MGR so here where response or login to response equals to what to say login response equals to login service oh sorry what auth service okay so it was auth service Dot login fine and it need a model which will be login model okay and it will be await now let's see if we are logged in then we will move to the now okay let's check here login response dot status code equals to one then we will move now manager Dot navigate to and we will navigate to the root path of this application okay so it is as simple as that so it is our login component okay and let's define here the logout component okay we will Define it later okay whatever whenever you want to create it you can create so let's create it right now add here add Razer component let's name it log out log out okay and we do not need anything here just a page directive let's name it log out and let's inject some Services here inject nav navigation manager navigation manager equals to now MGR and okay let's copy this thing from here to here okay and copy this guy from here to here and on initialize Pro protected override on initialized async and it will be a sync task and here we will wear result equals to Earth service actually I don't think our service logout service written anything so let's write here all service dot logout okay so no it is not returning anything okay after successful log out we will move to the login page now MGR Dot navigate to login okay so we have created our logout component and we have pretty much completed that is login component I guess we have completed okay so let's open this shared folder this nav menu folder and let's copy this guy here and paste it here login fine and here login that is fine and copies sorry copy this guy also and paste it here let's change it to logout okay actually let's remove it from here and we will do it somewhere else so let's open this main layout page and okay we will we will write it here so just copy this guy and paste it here okay and if I write here okay so let's copy this thing here nav link and let's paste it here okay and name it to login and copy it here and name it to log out href equals to logout login so if I write here authorized authorized View authorized and not authorized we will put login link into not authorized and this logout link to the authorized okay so let's build this application and let's test it out so let's test it out okay okay and run this application okay so we are getting little bit problem here and let's see what we can do here Okay so do not use this class here nav link I guess then we will be fine now link okay if I try to run it again and okay I need to build it first so let's stop it here and build solution now let's run it okay we need to do some more changes here I guess okay I think this div should be moved to here and let's see this guy should be removed these guys would be removed this guy should be removed okay so let's press here the hot reload button and let's see applying codes changes okay now we are fine we are not seeing the log out button because this button will be shown only after the login or when we are authorized the user logout button will be shown only after authorization okay so click here on the login so we moved here in the login controller if I try to press this button and it is asking me to validate actually it should be a password type so login and if I write here input type equals to password let's build this guy and run it again and here one more thing I have forget it should not be label should be username and should be password so press this hot reload and let's refresh this page Okay so I already created a user and I had normal user and admin user when I have created the web apis so keep that thing in my mind sorry keep that thing in your mind then actually I'm logging here with admin credentials so let's see the API is working or not okay and here we are successfully logged in and we can inspect inspect element and look here in application local storage and click here so here it is our token access token that it has created when we logged in so now let's create some views and components so let's create a dashboard component here okay let's create here the dashboard and not the dashboard yeah let's create component here and okay let's name it dashboard that is fine dashboard and just type here hey I am dashboard and something like that okay so let's click here page equals to dashboard fine and let's create a new component here and let's name it manage let's name it products fine and here page equals to products okay and true ducts fine so to protect this View and this View where it is the dashboard we need to do the same what we have done with the login and logout URL we have to use the authorized View and where is our dashboard actually yeah here so first of all what we are doing here authorize View sorry and here what we are going to do authorized and here not authorized okay so here we just write here you are not authorized fine and here what we are going to do just type here context dot user Dot identity dot name if I write here okay now it's fine we will do the same here in the products page and here we will just display your products are here so what we are going to do here we are going to add two routes and let's see okay so first of all what we are going to do we are going to do the same thing here authorized view okay and it is authorized fine and it is not authorized which is also fine if I actually let's put these links here in the authorized section and we will create are one more thing here and let's remove this non-authorized we do not need it here so let's create one more thing here and actually let's put it here here in the top [Music] control KD now our document is formatted let's be copy this guy and paste it here and let's change it to dashboard which is fine and don't forget to change the link trash board now we are going to copy these guys and yeah let's paste here and authorized View we will close the authorized View and authorized here and what we are going to do here rules equals to admin now this link will be only shown to the admin and it will be products okay here products okay so let's click here but we need to build our project first okay and let's test this thing out let's see how it is going so right now we are seeing here everything the product link and the all of other things so let's log out from here and here as you can see we are not seeing anything except this home link and login so let's try to log in with user that I already have created as I earlier mentioned and let's type here the password sorry I have typed the wrong one okay so now we are logged in and you cannot see the user you cannot see the user which is sorry you cannot see the products link here which is only shown to the admin base sorry admin role user Okay so I'm just gonna do one more thing here inside the login where it is okay let's find the login and it is here and we will navigate to the dashboard let's see how to load works or not okay we are fine I guess so let's log out from here and log it again so let's try to login with user okay so we haven't moved anywhere so what I am going to do I'm just going to close it and I'm trying to build it again so I'm not logged in now so let's try to fetch that protected view which is dashboard let's see what it is saying yeah you can see here dashboard and you are not authorized Okay so let's try to log in and here so here we have logged in and it is displaying the name of the user so let's log out and try to log in with admin okay so it is displaying the name of admin which was admin okay so what I am seeing here I am facing a problem so let's see what it is this if if I am entering login credential here means I am logging with admin then I'm not seeing here any admin related link which was products and here I am not seeing anything like that but when I am refreshing here then I am able to see that link here so that is the one problem so let's see what can I do for it and actually I have done something wrong here in auth provider so rather than using this username I have to use token here okay and here I need to do this what we have done here so new we have to pass the token from the we have to pass the claim from the token okay and now we have to change our service where we are passing where we are using that method and okay here it is okay so where it is login here and here we need to pass this login response content dot token so that's the change okay so let's build it again and run it okay so click here in login now let's try to login okay now everything is working fine so every link is showing here so let's log out from here and log in with user okay so here we are not able to see the product link in the navigation section so everything is working fine but we have one more problem here if I try to access this component directly without logging in here is writing here not authorized but actually I am able to see this component here so this dashboard is not defined inside the authorized View so here I am able to use this URL without even logging in so we have a solution for this we simply what we have to do first of all we need to change here in apps Razer file and here we need to Define this not authorized fine here we will write please log in first foreign so let's close it here and now we need to do one more thing here open these Pages which are authorized and these two pages are authorized so right here at the rate attribute authorized authorized and it does not have d so if I click here so let's copy this thing from here to Imports so that we do not need to import these settings in the next page Okay so copy this guy from here and let's close this dashboard and paste it here and it is a role based view or component so we have to write here price rule equals to add pin okay we are good let's run this application and let's see okay so if we try to access the dashboard now let's see what it will say so it is saying please login First okay so let's do what protest here if I log in with user credentials and if I try to so if I try to login with this user credential and after that let's try to access the admin admin URL and which is it products products let's see what it will say here it is saying please log in first so here it is our fully functional authentication app in pleasure webassembly so that's how the authentication Works in pleasure web assembly so if you find this video helpful then please don't forget to hit that like button it really matters to me and motivates me to create more content and let me know in the comments how this app works for you so that's it for today we will catch you later
Info
Channel: Ravindra Devrani
Views: 3,295
Rating: undefined out of 5
Keywords: blazor authentication, blazor authentication and authorization, role-based authorization in blazor webassembly, authentication and authorization in blazor webassembly
Id: erzpa0mTtRY
Channel Id: undefined
Length: 90min 15sec (5415 seconds)
Published: Fri Dec 30 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.