Introduction To Blazor Authentication in .NET 8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there and welcome to the code wrinkles Channel I think it's high time to also talk a little bit about authentication in the new blazer in net8 what I usually call Blazer SSR and therefore in this video we'll look into how authentication Works in this new blazer SSR by investigating the Blazer template that includes authentication with individual user account so let's go to the program.cs file and understand how things are set up here what we can see from this template is that we are using actually sqlite as a database and therefore we also have an application DB context so the template comes really with everything that you need to get started with authentication in Blazer and here we can already see the first change that is totally different from how it was set up in Blazer in the previous versions because you see that the first thing that we see here is this Builder Services add cascading authentication and if you can recall previously or in previous versions of bler where we had our routes we needed to wrap everything in this cascading authentication component however this is not needed anymore in this new blazer version since this is covered by what we have here the service add cascading authentication State then we see some other services that are added to the DI container and these are custom services that are defined in this project and I will talk about them just in a few seconds the last thing that we can see in this setup here is that we need to add authentication and for the authentication options we need to add the default scheme which would be an application scheme and if if we hover the mouse over it we can see that this string is actually a constant and if we go to it we see that it has this identity prefix and then Plus application and we also have here this default sign in scheme and we if we hover our Mouse on this we see that used as a default scheme by signing Asing HTP context so this is the default scheme that should be used and here in this case we see that this is an external scheme and it's also a constant which is the identity prefix and external so essentially we used to to different schemes depending whether we want to authenticate user using our own system or if we want to use some external logins and last but not least you also need to add the identity cookies because authentication is done based on setting an authentication cookie however I would like right now to scroll a little bit more down to the middleware section and here we can see that we don't have those middleware like user authentication and use authorization and this is very important so usually we would be accustomed to have something like this is like use authentication and use authorization however in Blazer we don't need to provide them explicitly if we use this use antiforgery now use antiforgery as the name imply adds antiforgery middleware to the pipeline so it allows you to kind of like easily have secure forms by using also antiforgery tokens however I have found out the hard way that if you use antiforgery and then you also use authentication and use authorization things will simply start to not work anymore so let's not delete this middleware because as said we don't need that now let's move one step forward and understand exactly what services do we have here from the identity perspective from authentication perspective and what they are doing so first we have these identity components and point route Builder extension and if you take a look at this these are actually minimal API routes that are created for different purposes now mainly I would say that they are used if you use external authentication providers because for instance here we have have this perform external login so here would be the challenge if we want to perform a login with an external provider and here we need to set up different things but as said there will be a dedicated video about this and we'll talk plenty about this endpoint and how this is used and when it is hit and what everything here actually does but then we have this map post for the logout and this is used basically when you are logging as user when you click the logout button then you simply just want to be logged out of the application and the way that is set up in bler right now now it's simply making a call to this endpoint that is registered here and then we have here the signin manager and sign out async then we have another route group for the manage part and here this map post to link external logins is actually one of the endpoints that is used when we want to perform authentication with an external login and once again we'll talk plenty about that in an upcoming video and here we have another map post for download personal data that kind of like implements the logic for downloading personal data now this topic is right now out of the scope for this video but I just wanted to show you and briefly explain you what this identity components endpoint route Builder extension class is for and how it's actually used then we have this identity no op email sender which is essentially basically implementing this IM email sender interface this interface in our case if we take a look at that implements some basic methods that are commonly used for sending emails for authentication purposes right now it has kind of like a default implementation but if you want to wire this up with your own email sending mechanism then you just need to implement the interface and Implement these necessary methods and Define exactly how you would send emails however the way that the template is set up right now is just using this let's say fake implementation that is in this identity no op email sender class then we have this identity redirect manager class that kind of like is responsible for doing a bunch of different redirects so I would see this very simple as a utility service that is called in different parts of our components that allow us to perform authentication and different tasks around authentication and the different ways that we might want to redirect so redirect then with a message redirect to a URL with certain information redirect also with the with the HTTP context so there are different things or different ways that we can possibly do redirects and all these ways in which we can do redirect instead of having them splitted around different parts of of the code base they are part of this identity redirect manager the next service is identity revalidating authentication State provider service is actually a vital one that is very very important and the common idea for this revalidation authentication state in Blazer is very simple it hasn't really changed from the previous versions of the Blazer engine the core concept of authentication State provider is that we need a mechanism to check if the user is still authenticated or not because you could have for instance a user that has two browser tabs open for instance and that user logs out from one tab but doesn't log out from the second one and then if the user goes to the second tab he should also be logged out there so to achieve this we need a way to kind of like check in regular time interval for instance or whenever we check the authentication state of the user if that user is still logged in or not and the way that this is implemented is very simple we have here a time span and this is the revalidation interval so it means that by default if nothing happens a revalidation will be done in this case each 30 minutes now the way this validation is done is actually very simple and it uses the user manager so first we use the user manager to actually get the user and then obviously if the user is null then we return false that because it means that we don't really have that user in our database so obviously the user is not authenticated now the second if here this else if kind of like checks if supports user security stamp now this is a feature that if you use ASP doet core identity by default it is supported so it will use a security time stamp and based on the comparison of the security time stamps it is able to validate if the user is still authenticated or not now if this is not enabled so you can disable it explicitly then we just return through because we don't know exactly how we need to validate this tication but if the user is there then we can assume that it is true obviously if you want to implement lement your own logic here you can do it really the way you want you have access to your database you have access to your user manager to your signin manager you have even access to any type of information really so you can do whatever type of logic you would like to do however in our case in this else what we do here is we get the principal time stamp from the login user and then we get the user time stamp that we have saved in the database and then the only thing that's done here is simply a compar so if these two different stamps match it match then it means that the user is still authenticated if those stamps don't match then it means that the user has logged out in the meantime and then therefore this will return false and as this will return false the entire application will notice hey the user has logged out and will behave accordingly last but not least we have this identity user accessor and it's really a very very simple service that just retrieves the user or that just retrieves a user based on a user principle that we get here or a claims principle to be more technically precise now the common task is we might want to do with authentication is usually register users and for this we have this register component and please note one important thing here everything really everything in this braer since it's fully SSR is based on razor components so we don't need to have CS HTML files anymore because here we can rely on the HTTP context to generate some correct and appropriate data that we can use in our components to actually make important decisions like registering or authenticating users now this is a very simple form and we will see exactly how this looks in practice just in a few minutes where we will provide some information about the user like the email the password the confirm password and so on now the idea is that we have this task register user where actually everything happens and if we take a look step by step at what we do here is we use regular sp. net core identities services to actually create this new user and registry so first of all we use the user store to set the username then we get an email store to store the email and we use this set email and then user input email and here we provide cancellation token none and once we have those two we can simply use the user manager to create this user providing also the password that the user provided in the form obviously if we have errors then we add the errors to the model and we just return now the logic is implemented by default here is that the next step after you do the registration you need to also confirm your email so in this case the implementation starting here from line 83 is regarding this specific task so first of all you would want to get once again the user by ID because right now you also have an identifier and here you use the user manager to generate to generate an email confirmation token now that token is then obviously encoded we then provide or create a callback URL and last but not least we use the email sender you know remember the the the the email sender implementation that I have showed just a little bit earlier and here we have this send confirmation link async and it should actually send the email and if the email confirmation is required that's another setting that we can perform or that we can set when we add authentication in program.cs we then can say that okay then redirect the user to this account register confirmation and this would take the user to the page where they should register their account now we will see exact with this fake implementation of the service we don't receive really an email but instead we get the link from the email basically displayed in our browser and we can click on that to verify our email address and that's really everything that we have in this register razor component or Blazer component so let's move now to the login and here we have just a very simple login form obviously and in this login form we see that we get some parameters here we get the HTTP context because we need this information from the form we get as form parameter inputs this input model that we have and from the query we get the return URL in the on initialized there is this very simple if and it checks that if you hit the login and if there is already an authentication cookie that cookie should be actually removed and that's for that's why it performs here just a sign out so the cookie will be removed and the login user method is actually the method that gets it when you hit the login button and it simply does validate your credentials so it us is the signing manager and the password sign in Asing that would essentially verify if that combination of the email and the password exist already in your database here we have some other decisions that we could possibly make but if everything is okay we just log the information that user login and we redirect to the return URL so let's now run the application and see exactly how this looks in practice so see we have here this hello world with this counter click me we can click the counter but if we go on out requ required we are actually redirect to login and I will talk about this redirect to login just in a few minutes from now so obviously right now I don't have any user here so I would like to have a user so let's add this one let's add also a password but I think I need to add a more complex one simply like this also confirm the password and then click register here we can see that we have this register confirmation and obviously here I didn't receive an email but I have this click here to conf confirm your account and this is contains the token that was generated for the email confirmation but instead of receiving it in an email I just got displayed it here in my web application so if I click on that we see that thank you for confirming your email so it means that I am a confirmed user so right now if I go to this login I can use my email I can use my password also H remember me and then click login and you see that right now I am logged in let's Now log out from this application and then close close the browser the next very important topic I would like to talk about because it's really a very very common practice that we want to achieve in our web applications in a lot of different circumstances is that if a user is not signed in we should automatically redirect the user to the login page and as you have seen just previously when I run the application if I'm not logged in I can still go to all the other components like the weather forecast the counter and so on and so forth so I want to prevent this implementing this idea of redirecting to login is actually very very simple here in this Blazer on net 8 but it is different than it was before in Blazer web assembly or Blazer server and the proper way to achieve this we already have in this template that contains the authentication part so let's take a look a little bit here in this manage folder and in this manage folder you see that we have this imports. Riser and in this import. Riser which is then kind of like applied to everything that is contained in this folder in the manage folder and if you have subfolder it would apply to the subfolders too and here we have this attribute and Microsoft spet core authorization authorized theoretically if you want to achieve this redirect login if you take this attribute this authorized attribute and move it into the let's call it the global imports. Riser which is here and we can go here and add it here at the end however right now if we would run the application we would get some errors because as we have implemented this redirect to loging globally so for the entire application when you try to access really any URL we will be redirected to login but when we try to access the login we will be once again redirected to login so it will be a continuous loop that's why what we need to do is come back here to this login and for this login component we want to specify the attribute allow Anonymous and this will make sure that requests that are Anonymous are able to actually display this login page so now if if you run the application you can see that I was automatically redirected to login and if I click on home I'm redirected to login if I click on counter I'm still redirected to login obviously in practice we would also want to allow Anonymous also on the register because right now when we click on register we are also redirected to the login obviously and we wouldn't be able to login if we don't have a user already last but not least I would like to show you this authentication revalidation in action so the only thing that I will do here I will change this to be not 30 minutes but to be only just 1 minute so here I have the application and I will use my email address to log in now let me go to another browser window and I will just also do this exact same thing obviously in this case I am already authenticated because I already have an authentication cookie for this website now let me go here on this first browser and let me then here click on log out and then I will go automatically to the second one and I will just wait here for 1 minute it could be that it's less than 1 minute because it kind of like depends when the last time the revalidation was done now the thing is that you won't be automatically logged out because this browser or this window is kind of like static so nothing happened with the server anymore but for instance if I want to click on counter here you see that I was redirected to login so because I logged out from this browser window now here in this other browser window when I wanted to navigate to any custom component the r validation was actually done in the background and the moment I wanted to navigate it recognized that I am not authenticated anymore and therefore I was redirected to login bottom line is that right now we have a very good and common understanding about how authentication works and how the authentication is designed in this new blazer in net 8 and that's a solid foundation for us to maybe go and investigate further in other videos how we can authenticate for instance with external providers and how we can Implement also authorization how we can work with policies but I just wanted to have this Common Ground defined previously if you did enjoy this video don't forget to hit a thumbs up button and like it you will help us to make it easier to discover for others that might have find it useful as well and if you for the first time on the Channel smash the Subscribe button so that you don't miss anything new that will come up on this channel and if you have any question or if you have any idea or suggestions please don't be shy and head over to the comment section and leave your comment I would be more than happy to get in touch with you this being said said thank you very much for watching and until the next time I wish you the very best
Info
Channel: Codewrinkles
Views: 6,435
Rating: undefined out of 5
Keywords:
Id: asa2ucbZlCI
Channel Id: undefined
Length: 18min 32sec (1112 seconds)
Published: Sun Feb 04 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.