Role based Authorization in ASP.NET Core (.NET 7)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to the Royal coding YouTube channel my name is Anton and today we're going to be talking about a role-based authorization if you're working with asp.net core chances are you're going to be using identity framework MVC Entity framework and you might be using role-based authorization now in my authorization video I do talk about role-based authorization although I just came over I say role-based authorization is just claims and policies so in this video we're gonna specifically dive in on role-based authorization and take a look at how it's implemented where it's triggered and what are the pieces that it's composed of before I begin the video I want to let you know that I have a course out the c-sharp programming course where I teach programming through c-sharp so if you want to know programming as I know it I highly recommend you go ahead and check it out the course is meant to be evolving over time so if you get the lifetime purchase you get all the present and future content that I'm going to be adding to that course the course is currently aimed at beginner level however there will be more advanced stuff added on later thank you for listening to my advert if you did and let's go ahead and get started so we have the roles project and The Rose Project contains two controllers and program CS all we're adding is authentication and just regular cookie authentication authorization controllers and by the way if we take a look at that controllers at controller score under the hood it is going to try to add authorization even if you haven't actually added authentication or anything like that right so with controllers this authorization is pretty much already registered I then have map controllers and use authentication use authorization for my middleware closing this on the home controller we have two routes the index route and the secret route where I'm asking for the role of admin on the account controller where we have the login endpoint all I'm doing is manually signing in under the quick authentication schema with this claims identity that only has one claim of the name identifier so with this claims principle no roles in sight if you watch my authorization videos you're gonna know that if we go into program CS add authorization authorization middleware you're gonna be able to scroll down here and come to this point where the policy is being loaded up you can see here I have a breakpoint because this is the main point where role-based authorization is actually loaded so again if you're a beginner as the request is coming in it's going through this middleware and at this point we're trying to apply role-based authorization even though that we haven't added any policy or anything like that okay I have the application running let's go ahead over here we are currently in the at the index route and if I just go to secret and I get a 404 here the reason is because I'm not authorized I just get redirected if I go ahead and attach a debugger to my roles process and by the way if you're using something like vs code or Visual Studio I don't know if this is possible to decompile the code place a breakpoint in there and then actually see the debugger stop there so this is one of the main reasons I would recommend to actually use writer because I decompiled the code I placed a breakpoint there and now if I hit secret and I'll see our application stop here now what happened before this doesn't really matter policy currently is no we're trying to get a new one we have however some authorization data and the authorization data is coming from the endpoint the end point hopefully you can see here is homecontroller.secret the endpoint originally is fetched from the context and the context is the HTTP context so if you didn't know you have information about which endpoint is being invoked on the HTTP context and this is applied after the you use routing middleware that's the middleware which figures out which endpoint is going to be called nevertheless we know what endpoint we're calling we know what authorization data we want for that endpoint we can see that we're asking for role of admin and some interesting things happen inside this combined async middleware if I step in and I will scroll down to this if statement over here where we're going to reach because we haven't registered any of our authorization policies and the authorization datum or data will have the roles which are going to be split by comma so they're all split over here whatever endpoint that we were calling over here it requires an admin role the interesting thing here is that it will create a new policy Builder so it's creating a policy on the Fly and it will call the require role method on the policy Builder which will add the role author requirement okay which is also the authorization Handler in the handle requirement async this is the bit which is actually trying to figure out if the current user is allowed to access the resource or not the real piece of logic which is going to be executed here is on the requirement we're gonna check which roles are allowed on this endpoint and then we're gonna call the is enroll function on the user which well it's a little bit hard to see here but it's going to be the claims principle okay if we back out and we take a look at is enroll we're going to see that it is just a for Loop iterating over the identities inside the claims principle and it's taking a look at the individual role claim type on the identity and Compares it to the role which is going to be one of the allowed roles okay and again if we take a look at is enroll it is calling the has claim so this is how role-based authentication is really built up out of policies and claims we're just checking whatever role claim is configured on the current identity and then a policy is being built up on the fly to essentially invoke this logic okay and this is how we are essentially flying past this and we are ending up on the 404 because we're not allowed now that we have this information when we're gonna go to the account controller and let me close everything else when we're looking at this piece of code we now know we need two things a claim which is going to represent a role and just to kind of push the issue forward that we really understand this I can say that I am going to represent my role claim Extravaganza right this can be named whatever you'd like it to be all right and then the role that we're looking for is going to be admin the second thing that we need is that role claim type which is going to look for this specific claim this should be accessible on the claims identity although we don't have it here the real way that you set it is if we open up the roles identity we scroll down we're gonna see various Constructors where you can actually Supply the name type and the role type if you're wondering about the name type it is very similar to role type but name type is actually going to populate the name of the claims principle rather than look for the role so back to the accounts controller to the claims identity we're gonna say that name type or now it's going to be null and the main thing that we're interested interested in is role type which we're saying these claim types are going to be representing the role Concept in asp.net core with that running and my debugger should detach or maybe not let's go ahead close it down this is going to restart we're going to come back we are going to log in I'm gonna open this up I'm gonna make sure that I have my cookie over here I'm now gonna go to secret and we will be able to reach the secret route coming back to the code let's summarize role-based authorization it's built out of claims which are basically key value Pairs and the key is meant to say that this is a roll and then what value do you hold the role type is really just a pointer that you're looking for these keys and these are going to be the representatives of the roles now if we go into program CS we know now that inside use authorization middleware there is logic that basically says there is some authorization data on the endpoint it doesn't have a configured policy are there any specified roles if there are go ahead and start building up a new policy and then it adds the role authorization requirement to it which is going to use the role claim type to check if the user contains the claim one question you may have is it building this policy all the time no it is only going to build it once and is going to Cache it so if we go back into the authorization middleware and it will help if I will close this down let's scroll to right over here we will see that this policy is going to be constructed and then as long as it's not null we're going to store it in the cache next time around when it's going to enter the middleware the policy is going to be retrieved from this cache okay and that's all you need to know now with the account controller over here we've done the construction of the claims principle manually let's go ahead and see how identity framework is going to do it we're going to come over to the roles identity which is pretty much a copy though I set up identity framework with the default identity DB context to store the users and I'm not even connected to a database I actually want to say that I'm going to use the in-memory database and call it my DB I will then also need to see the user so I will get a Services over here create a scope and surface my user manager now that we have the user manager I can go ahead and create an actual user give the user some simple information and a password of well password I will need to wait on this once we have a user I can use the user manager to add the user to a role or to multiple roles so here let's take the user take him out not take him out as in you know with a gun and shoot him but rather into its own variable well I'll wait on this result and we will add to the admin role I'll delete this new line and for the seating logic this is about as much as you need if we take the user manager we'll go to the controllers we will go to the account controllers now that you have the user in the database I'm not going to be supplying all the credentials over here I will grab the sign in manager it is still going to be for the identity user and the sign in manager is going to do some very very similar work let's actually give this a body I think it will be a little bit easier to read we'll take the sign in manager and we will sign in async or where is it password sign in async where we Supply the username and the password the username for us was test.com and the password is password we also then have some options which I would say don't really matter at this point we will await and then return okay the main thing we want to understand here is what does identity framework do similar to how we do it in the account controller over here because we're constructing a claims principle and then we're adding it behind this cookie authentication in the account controller over here if we go inside password async and we're going to see that it's using the user manager to find the user by name once we have the user we're going to go into password sign in async and here again for some reason we're just verifying that the user is not null and then we check password sign in async so we try to check it we go inside we have some kind of check that might error out and then again we use the user manager to communicate with the database to check if the password is correct which is just going to use Entity framework core under the hood so let's head on out of here at this point the password should be correct all it should do in the end is just return that sign out is successful we're going to now back out a couple of times and this may look a little bit confusing but check password sign in I think this should return an attempt if the attempt is successful we're gonna call sign in or two-factor async and here we don't have to factor authentication enabled so we bypass it and go a little bit further this bit here is for external authentication which you just actually want to clean up but after that you enter one of these two methods if you don't have a login provider or if you have a login provider is an external login provider so if you're trying to externally authenticate with Google you're going to enter into this bottom part so sign in with claim async we have the user that is persistent and the new claim let's go ahead and dive a little bit deeper a bunch of more stuff in here let's dive even more deeper and here is the method of Interest create user principle async let's go ahead and dive into there we have a claims Factory with create async let's go ahead and keep going down into this method then here we have generate claims async which returns a claim of his identity so we want to go ahead and dive a little bit further in the generate claims async method we are extracting user ID and username from the database I'm not sure whose idea was it to make this service so chatty with the database but here we have our claims identity identity application where username claim type and role claim type is being placed into the claims identity and you will see that options claims identity you can actually configure this stuff from the options so this is identity options so you can see where these options are going to be used if you come back to program Cs and you go over here when you hover over the so this is that identity options so o claims identity you can actually configure what you want your role claim to look like so whenever you're adding a claim so add claim and this is going to be some kind of claim of role admin something like this and you want to change the default Microsoft claims you can actually do that but hopefully with all this stuff it paints a clearer picture of how role-based authorization works and how it's all assembled in asp.net core and identity and MVC let's go ahead and run this application and see it works so dot watch looks like a role admin doesn't exist and that is because I actually forgot that there is actually a role manager that you need to be using and this is going to be I think identity roll so a role manager where you want to go ahead and create a role which is going to be a new identity role and the name will be admin semicolonian let's wait on this go over here should be restarted so try to reach secret we get redirected to login which we don't have we go to login I have not changed the route on here so this is actually going to be account slash login so account slash login will be authenticated successfully so if we take a look at this you can see that this identity cookie is going to be representing this identity framework authentication session if I go to secret now I will be able to reach the secret route and this is pretty much it thank you very much for watching hopefully you've enjoyed it and you can clearly see how role-based authorization is built out of claims and policies and if you're wondering about the usage it is a pre-configured solution which means it's not as flexible because policies and claims are your smaller building blocks you have more flexibility but you're gonna need to write a little bit more code with roles less flexibility but less boilerplate code again thank you very much for watching if you enjoyed this video don't forget to leave a like subscribe if you have any questions make sure to leave them in the comments section don't forget to check out the authentication playlist if you would like the source code for this video and my other videos please come support me on my patreon I will greatly appreciate it very very big thank you to all of my current patreon supporters your help is greatly appreciated if you're still listening and you're a beginner in c-sharp go ahead and check out my course I think you will enjoy it a lot as always thank you for watching I'll see you later
Info
Channel: Raw Coding
Views: 15,107
Rating: undefined out of 5
Keywords: asp.net core, mvc, role, claim, policy, deep dive, understanding, explained, csharp, controllers, authroization, auth
Id: W5T6713KRzg
Channel Id: undefined
Length: 16min 18sec (978 seconds)
Published: Tue Mar 07 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.