.NET 6 Blazor 🔥 Authentication & Authorization #2 (HTTP Header & NotifyAuthenticationStateChanged())

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello friends patrick god here and i don't want to say i told you so but i told you so here we are with part two of blazer authorization and authentication and so on we covered a lot already i think well the basic client stuff in the first tutorial check it out here please or in the video description and now it's time to combine this with the web api so what we will do in this tutorial now is we will put the token and the default http request header we will of course cover logging in a user because with that we will make a web service call and create a json web token and then we will return this thing store this with the blazer local storage package great stuff by chrysanthe kudos to him store the token in the local storage and then the authentication step provider will get the token from there and then again we will have a look is the user authenticated or not and additionally to that we will also make use of this event i told you from the last time meaning if we have a component that is not directly connected to the authentication state provider let's say hope you get what i mean if you watch the tutorial you will know what i mean we will erase this sweet event and then the component will know if the user is authenticated or not and now there's only one thing i want to tell you thank you thank you so much for 8 000 subscribers this is unbelievable well we got i think 7 000 in the beginning of january kinda and now we've already got eight so wow this is amazing guys thank you so so much this means the world to me maybe we can get to 10k this year i don't know it's it's just crazy what is happening in the last couple of weeks so thank you so much for 8k if you haven't subscribed yet and like these videos here would be great if you subscribe maybe even click the like button and don't forget the bell icon so you will get a notification if a new video is uploaded additionally maybe the newsletter is interesting for you i send an email once a week at most and there you will get early access to these videos and also to online courses by me for instance the e-commerce course which is coming this month i promise hope i can keep this promise but i'm pretty sure it is coming and the last thing as always guys thank you so so much for all your donations all the coffee i can really really use the coffee lately we've got i think it's it's called sleep regression if you have a toddler i think you know what i mean and the nights are getting harder again i thought we're done everything is fine now but it seems that's not the case anyways long story short enjoy the tutorial all right quick recap as you can see here i've already opened the project it is available on github so please have a look at the video description there you will find the link to the github repository and what we did in essence in the last tutorial in the first part of this blazer authentication authorization tutorial stuff series whatever i hope it's it's done with this second part but if not again write it down in the comments but anyways what we did is we created this custom authstate provider i think this is one of the most important things here because that thing decides if a user is authenticated or not if you wanna get to the details please again have a look at the first part of this tutorial but what we get here is this hard-coded token and with the help of this token we create a claims identity we parsed this thing got the code for from steve anderson here and when this json web token is parsed we can create this claims principle which is a user then the state we return this state and also re-re-erase the notify authentication state changed event and this will be important among others others the other things this will be important for this tutorial now and please excuse me if i make some errors some errors occur because it is at 10 o'clock and this is really late for me sun is sleeping but not very well anyways so we do this here and or we did this and additionally in the counter page we use the authorized view component with the authorized and not authorized view so here we can show content depending on the current state of the user and also important here in the app razer file we added the the authorized route view instead of just the roused route view we'll use this thing here also to have a little fun and then the cascading authentication state i think this was everything or most of the stuff we did in the last tutorial and the first part and now what i want to do is again as i told you uh we make use of the server project here so i won't use the best practices here for that please refer to other tutorials of my channel or in my channel or i have to make i have to add this little commercial here of course you can always have a look at my online courses for instance the blazer boot camp there we will use best practices to do that and do not forget the e-commerce course coming in the next couple of days and here we will just add another controller an auth controller that will again just return the hard-coded token if you want to know how to create a json web token have a look at the info card now there you can see the video where you create this whole thing with the cryptography algorithm and so on but what we will do is we just hard code this stuff but still we will add a login form where the user can enter anything in essence and we get the proper token back we return this thing and then we will change something on the on the side on our application and this is then interesting because some components will know that something has changed that the authentication state has changed although they do not ask the authentication state provider directly okay so this just for another introduction here and now i would say we just start with the server project here so what i want to do again is add another controller we see the weather controller with the forecast controller here already nice stuff example stuff and we add another one here in the controllers folder we right click and add another controller and this is an empty api controller like that stuff it's empty so i can do whatever i want i have no generated code here and sometimes this is just better for me well auth controller it is and what we do here is again a simple method just a post method that you would use to log in a user and actually then we would forward this request to a service with the repository pattern inject the service and so on and then this service and this method then of the service would check if the given username and password is correct in this login method that we will create now but again it's an http post method this is the http method we are going to use and public async task action result is okay but we use the class here and we return a string which is again the token the method is called login and what we could do just for fun is actually use a dto so if you do not know what this is you see it now so in our shared project now we add a new class and for instance we can call this user login dto so dto stands for data transfer object and this just means let's make this public jesus public here it is and this just means data transfer object that this this object would not be mapped to the database so this is not a user entity in essence with an id a username a hashed password a password sort maybe an address date of birth i don't know whatever you want to see here we only want that what intellicode is suggesting here a username i can make this empty and i would like to write it like that and also the password i think there was already the suggestion okay and this is also an empty string by default and that's it so this is our dto again meaning data transfer object we only use this class here to transfer data for the login and now here in our auth controller we can use it so user login dto almost dto we add the using directive here to the shared project call this request for instance and then actually what we would do is we would well again check the username and the password to do some stuff with the request but in our case now this is really just to show you how you could do it but we don't do anything with that i really just wanted to return the token so um we got it already in our off state provider there it is and now we just add it here so it's still hard coded and again i know i'm repeating this a lot today but this is really just for the blazer authentication stuff so usually i would never do that um but i think it's too much for this for this little video here and we we covered this on another in another video so bear with me if you think jesus christ what is this guy doing here he can't do it like that please show me how it's done completely but then again this would be a complete course that would take several hours i think anyways um re-return the token here all right so that's really it's of course we do not have an authentic an async call here but that would be the server part in essence we have a login method and we have also an object here and we return the token then okay that's nice and with that out of the way we can actually continue already with the client and what i want to do here now is we add a login page where we make use of this post call here and then after logging in and in our case it will always be successful right so we get the token and after we get the token from the server i want to store it in the local storage we need or we will use a little uh nuget package for that and then we call the authentication step provider and the authentication state provider then does exactly the same thing as in the first tutorial but let's do it again one step after another in our pages folder we add a new razer component and that would be called login and since this is a page we add the page directive and this would be the route then and now we need some stuff actually we need the again the shared project but we can actually do that here i'm prepared a little this time let's see if it helps shared all right so we got that out of the way and then we need the http client similar to the to the fetch data page here with the weather forecast although again i have to tell you that i would not do this in uh let's say in the bigger application or in production again here i would use a service for that we do this in the quad videos for instance uh place a web assembly here on youtube so inject this thing then and the service and the service then would inject the http client and make the call but again let's do it quick so we need the http client inject http client call this http maybe we also need the authentication state provider so authentication state provider auth state provider and we already need the local storage and for that we right click the client project and add a new get package here local storage blazer local storage it is 1.2 million downloads that's great so great for chrysante this is really a beautiful library if you don't want to use this thing here you would have to use the js runtime and then call the local storage methods yourself in essence this works as well so up to you um now we have to register this thing real quick here in the program cs of our client project we call builder and then add blazered local storage i think that's it yeah almost our services of course services and yes that's the one um let's make this global maybe it could be the case that we need it again and also why not add it here as well in the imports so we're not you do not get bothered by this thing alright so we've got in our login page we've got now we have to first inject the i local storage service as you can see just to mention and there's also a synchronous local storage service usually or by default you would use the asynchronous one but could be the case that you need to call a method synchronously for that there's the sync local storage service but we use the i local storage service that is asynchronous and provides lots of asynchronous methods here we call this thing just local storage and now we're able to use it now in the code block the first thing we need is our user login dto our model because we will add an edit form and this edit form needs a model and also a method and in this edit form then we use the built-in components of blazer input text fields in essence where we entered the username and the password okay but first we need a model for that so this would be our user model here user login dto this is a new user login dto like that and now regarding the edit form this thing here we say our model for that is the user and then we also need to call a method on submit just submit we've also got on valid submit on invalid submit lots of fun stuff i can create lots of videos about that stuff of course so got that covered now and yeah we need the method of course so async task handle login it is but before we write that method uh let's add our our form in essence and this will be really ugly i'm pretty lazy today do not want to add some cascading style sheets or anything but i think it's totally sufficient to do it like that so we've got a label that's that's already a lot and now the input text component and for that we find the value user and then the user name see that so we've got our model here that's nice and now we can bind to a specific property here i love that all right that's the first one and now the password of course forgot the id username okay password the id password here [Music] then label as password we bind to the password and we say the type is also password okay and then the last thing would be the button here type submit that's important and please log me in do it okay so that would be already our edit form i hope and after that now the handle login method again we make a call or do you want to see that already maybe we can we can let's have a look here so i save this with the proper shortcut yep okay now where are we here we are and now we have to go to the login page there it is nice you see we can do one thing one tiny thing button button primary yeah at least a little bit design stuff as you can see nothing happens here it's calling the handle login method but we can enter whatever we want and now i want to log in the user so the first thing again the http call for that we get a result back so await http and then post as json async and the url would be api off double check we've got our auth controller and you can see here on top this is the route so the string api and then forward slash and this is the convention controller and this is just the term b for the controller term so it really is just off and as you can see here that's a bit different so we do not have the api string here just controller and then this would be weather forecast and as you can see in the fetch data page this is then the uh the actual route for the call all right a little bit different but also works of course so api auth it is and since this is a post call we add our object now and that would be the user again we do nothing with this thing this is just to show you how it could be done and after that we get the token back but the result as you can see here is an http response message because post as json async returns a task with a http response message so how do we get our token now well when you know it it's easy so our token is now wait results and this thing has a content and then we can say read as string async since we only get the string from the server if you would return a complex object then you would use something like that like that read from json async and then you add the type in the angle brackets here and then this would work as well okay so but we only have a string and with that we get our token and let's let's check that so for instance we can just write it to the console save everything it's rebuilding nope don't want to save that do it and we get our token right so i can enter anything i want here and i get the same token okay this already works but now this is now the fun part really we store this in the local storage so local storage and then set item async would be enough set item async we call this thing token and then also here token let's check that it's rebuilding okay never do it and now in our application tab here we can have a look at the local storage and there you see our token isn't that nice it's great huh so with that we now have the token here and then we can call the auth state provider weights off state provider get authentication state async and now we have to change the method a little bit because we want to get this token now from the local storage and then decide if the user is authenticated or not so let's go to the custom offstate provider here we don't need this now actually but we will use the local storage to get it right before we can do that we have to inject it so let's comment this out first we add a constructor here and we inject the i a local storage service call it local storage and then we create and assign this field here and now we actually get the token with the weights local storage get item string async and that would be our token and now what we can do we just say we've got an unauthenticated user first that would be the empty identity and now if the token is not null or empty then we use it to set the other identity the authenticated or authorized identity maybe so if string is empty token and this is not the case then we say identity is this uh new claims identity with the actual token okay and with that now we well we we can we can call the off state provider in essence and ask the auth state provider to decide by itself okay do i have a token if so then i try to parse this thing and set the claims identity and if not um yeah i do not have an authenticated user and that's that alright now the next step would be after logging in and asking the authentication state provider to set the current authentication state of the current user that we have another component in essence that uses this new authentication state and this component will then make use of the notify authentication state changed event and what i want to do is a pretty simple component in essence let's open up the page here you see the top menu here kinda we've got the about link and what i wanna do here is i just wanna add a login button and when the user clicks on a login then we go to the login page and when the user is logged in and this is now crucial after logging in the button should change and write or show a log out button without really telling the component that it should display this button it just knows it's like magic it just knows that the user is now authenticated so let's try that okay we go back to visual studio and now in our shared folder we add a new component and this component now a really creative name login logout button okay and now this thing needs some stuff actually the first thing what i want to do is when the user clicks on the login button then i want to navigate the user to just the login page simple as that we use the navigation manager for that so at inject navigation manager navigation manager additionally again we need the local storage service because when the user logs out what we want to do is then we remove the item from the local storage that the token from the local storage and again called the auth state provider because then the token is null it's empty so the authentication step provider should set the auth state again just to not authenticate it and then with the notify of state changed event tell every component that wants to know that the user is now not authenticated and not authorized anymore so inject i local storage service local storage and the last thing again the authentication step provider so authentication state provider authstate provider maybe alright and now we need the authorized view with authorized and not authorized and maybe you already guessed it these are actually the components that are listening to the notify of state changed event so this thing here when this thing is raised these components know okay something something is different now so in the case the user is authorized we show a button and on click we call a logout method log out maybe also add a little class here button button primary and in essence we do the same or something similar here in the case the user is not authorized we just call a login method call this also login and maybe we can change that to danger is there danger button danger yeah that's it nice okay so this would be red then i think and now the actual method so first the login method we call the navigation manager with navigate to and then just login that's our login page and now regarding logout it's an async method task logout and again we say await local storage remove item async and that would be our token and then again the off day provider auth state provider get authentication state async all right that's the button and now of course we have to edit somewhere so in our main layouts here's the about link and maybe we can just remove it and add our new login logout button all right and now let's see there's our page it's not rebuilding all right let's have a look again now it is well let's see something is wrong okay let's have a look at the console custom offset provider it's not empty and it's absolutely correct okay let's have a look and our application what happens if we remove this and reload this works okay you can go to home login this even doesn't work okay where's that [Music] okay let's just try a console right line hello oh jesus okay okay this is what i wanted i okay let's uh log in what's happening here index out of bounds that's the token oh yeah the token looks really short come on okay let's see i've got it here i think ah jesus okay see that want to hard code the token and that's what i get now so let's so let's close this and add the token here now now it should be correct so there really was an error with the token did not assume that let's restart now again and i think [Music] i mean now of course remove the token and no reload everything should work as expected yep can go to home we can log in we can log in and it works and now this is actually what i wanted to show you this is the whole magic we see the log out button so this thing really changed all right and we did not actively ask this component for that the only thing that was happening was that the authentication state provider raised the notify of state changed event i think i tend to forget the name another thing i want to show you you know here in our counter page and this is what we did in the first tutorial in the first part of this thing you're authorized as tony stark right but when i now log out it should be the same thing we do not actually tell the component that something has changed regarding the authentication state but when we click log out now we see that we are not authenticated anymore and this is how it should work now there's one last thing missing i want to show you and this is adding the token to the default request header of your calls because what we did so far is let's have a look again in uh for instance the fetch data page we make this call right so when we go back to our page and go to fetch data and have a look at the network tab here what the forecast it is we filter this and here now what we can see is uh this is the call all right but in our headers we do not add an authentication header or a bearer token in essence so when i even when i log in say do it see we are now logged in and now i go to fetch data again we see the call but we do not see the token added to the header now why would you want to do that well in essence this is the or one of the main reasons why we do all this authentication stuff we want to well and use json web tokens in essence well the the the thing is when a user is logging in with his or her credentials then we know okay everything is fine the user is the one or at least the user knows the credentials so it seems everything is all right and for instance the user is allowed to access the weather forecast data now but to make this weather forecast call we cannot just assume that the login worked and now we just let the user do or let the user access all that weather forecast data just because the user logged in successfully once we wanna know with every single web service call we wanna know if this is the authorized user right so one way would be to just add the user credentials meaning username and password for every single call but well i think the usability would not be that great in this case so what we can do now with the json web token of course is the token tells the server that this is the authorized user there are some more details to that with the secret key we would add in the app settings json again have a look at the info cards there is the tutorial where you learn this stuff but let's just assume the server knows with the given token everything is fine so we can use this token now with every single web service call and long story short let's just add the token to the header of every web service call if we got a token and for that we use the authentication step provider again so back here and we already got our if statement here and now that's a better practice anyways to add the curly braces so if we have a token now one thing is we set the identity but the other thing would be to set the default header if we do not have a token or by default we set the default authorization header to null and excuse me please if i set authentication header before sometimes i do that i don't know why it's just what i do but it is actually the authorization header not authentication so default request headers and we need the http client for that of course so http client http it is and that's the one okay and now we have it and here's the authorization and this thing would be null in that case so we have no token and in that case we have no identity and we do not set anything to the authorization header but if we have one we have a token in essence what we do then is again http default request header now it's suggested see authorization and in here now we say new authentication header value authentication had a value that's the one and we had the using directive i hope authenti i told you it's late authentic k authentication okay now it works and in here now this is a barrel token and then we've got our token here and one thing that happens is again let's have a look at the application tab you see the you see the quotation marks here right we don't want that so let's just replace the quotation marks like that and three in essence just remove them and now this should work okay so i somehow had to rebuild this thing but now in the network tab you can see it here we are not logged in and we do not see an authentication header somewhere right now when we log in say do it go back to fetch data and now we see our authorization header all right nice and now when we would add something like that the authorized attributes again this would not work just like that we have to also add some middleware for that stuff again there are videos on my channel where we do all this and when we realize that then we can really say okay we need this authorization header to be set and only then we get the weather forecast data but if the user is logged out not authenticated or not authorized regarding the role for instance then the user is not allowed to see the data all right i think this is really now everything i wanted to show you so that's it i hope now you know everything if not write it down in the comment section and i will do my best to create another video for you guys of course thank you very very much for clicking the like button and maybe even subscribing to my channel don't forget to hit the bell icon for notification about new uploaded videos apart from that maybe again the newsletter could be something for you if you want early access to all these videos upcoming online courses and so on then please consider subscribing to the newsletter and last not least again thank you so so much for all your support your coffees donations kofis this means the world to me and as you can see my eyes are well it is late in my for me it's late it's 11 o'clock oh yeah it is for me it's late you know the drill little boy who is asleep now here's my uh my baby phone as you can see and uh pretty happy that it is silent now so yeah enough about that thank you very much for watching thank you for your time and i hope i see you next time take care you
Info
Channel: Patrick God
Views: 18,417
Rating: undefined out of 5
Keywords:
Id: kOnMMKxwm3I
Channel Id: undefined
Length: 41min 43sec (2503 seconds)
Published: Tue Jan 25 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.