Asp.Net Core AUTHORIZATION Made EASY

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there and welcome to the code wrinkles Channel authorization in asp.net core often seems to be a very hard topic but in the end trust me it's not that complicated and I'll prove it to you because in this video I'll show you what I think would be the easiest approach to understanding authorization in asp.net core and before we dive into code let me briefly explain why I think that sometimes authorization seems to be very hard to grasp and the primary reason for this is the authorization itself has a lot of different building blocks and the flaws of the most of the documentation out there and different tutorials is that they try to teach you all the building block at once and grasping all the building block at once is not something that comes very easy so my approach to authorization is a little bit different I want to strip out each building block from this authorization until we remain with the core when we understand that then we can add one building block at a time and authorization will become very easy and the first two things that usually get mixed up when we talk about authorization is these two concepts of authentication and authorization they are quite different authentication is the process through which you need to prove your identity based on some credentials and most often also based on a multi-factor authentication problem authorization on the other side is the process of defining if you have access to certain actions in an application or not it's true authorization relies on authentication because if we don't have a not dedicated user then we cannot Define if the user can access or can perform certain actions in your application or not and usually the result of an authentication process is either a notification cookie or a Json web token now the cool thing in dotnet is that we have all the tools at our disposal to just generate for instance gwts and then use them for authorization purposes so let me show you what I mean by that first of all we need to go to the terminal and here in the terminal we are currently in the root directory where the entire solution is and to be able to create some Json web tokens we need to go the folder where we have the project so we have the CD and then to API and once we are here dotnet provides us with a very nice tool which is this dotnet user jwts and then we can create and the first type of Json WT that we want to create is a one that would also contain the role of administrator so if we just hit enter here we will see that we just get this Json web token back so I'll just copy it and I'll move it to a notepad now in our application we will have some requirements to restrict access to certain endpoints for users that are under a certain age therefore we need to create two different Json web tokens for that the first one we'll create with an edge that is actually okay and you see that to do this we use these claims and we Define a claim which is named age and which has the value 20. so if we click here on this one we we get this token back and once again I'll copy to a notepad now let's create also a token or an edge that will not be okay for our application so it would be exactly the same the only difference is that in this case the value of the age is 17. so let's generate this token and copy it to our notepad and last but not least let's also generate a just a regular token without any role and without any additional claim so we also copy this to our notepad now there are a few things that I wanted to show you because everything is made to work out of the box now when you create such a Json web token for the first time what it happens is that it automatically adds here some authentication configuration to our app settings.development.json and this will make sure that we will add this Json Bearer scheme and that we will have the valid audiences and the valid issuer so basically all the things needed for asp.net core to validate the token which is another building block of authorization on which we don't want to constant three today the final thing that I would like to show you is this jwt.io website and that's a very nice feature and tool to use by developers because it allows you to place this Json web token here for instance this is the first one that we have created and it shows you actually what information is contained on that Json web token and if we take a look here we see that okay we have some different standard information that we have on all jwts but we also have this raw information which is administrator so remember that's exactly the role that we have added also if we put if we place a token here that also contains the age you see that once again we have the default information that we have on tokens but then we have these information about age and it is the value 20 and usually this type of information like age or other type of such information that you can provide on Json web tokens when you create them our code claims so you will hear this a lot a claim is nothing else then a key and the value so a piece of information that you can use to your advantage when it comes to performing authorization now that we have several different Json web tokens we can simulate requests coming from four different users so how do we perform authorization in asp.net core well the answer is actually very simple when a request comes in in that specific request in asp.net core we have a lot of information about the authenticated user and about the request itself and we can use that information to custom Define if the user can access a certain endpoint or not the first thing that we will need to actually use authentication and authorization is a nuget package and I have already installed the package and the name of this package is Microsoft asp.net for authentication jot better with this in place we just need to add some services that will allow us to work with authentication and authorization so it just simply builds or Services add authentication and add JW tip there because we will work with Json web tokens in this API and then we have Builder services and authorization and then the other thing is that we need to also adhere to the middleware pipeline and authentication middleware and this is app use authentication and now as we have everything in place let me just adhere this dummy middleware because this will help us by placing a breakpoint here help us understand exactly what information hp.net core provides us regarding the authenticated users and how it provides this information so let me debug this application and then move over to postman let's remove the trees or no we need an authorization header but first of all we need to make sure that it contains the Json web token or one of the Json web tokens that we have created previously and I will use here the very simple Json web token that doesn't have a role and it doesn't have any additional information to it let me just hit the get and let's click sent okay so now we did hit the breakpoint and in this breakpoint basically we are in the middleware and I wanted us to stop here because in the Middle where we get information about the request and we get this information in the HTTP context and you see that we have this context which is the default context now on the HTTP context there is a lot of information that we get and potentially really every piece of information from the HTTP context you can use to define if a user has access to the specific endpoint or not however what's very important for us now is this user now the idea is that as long as the request is authenticated we will have this user and we'll have this is authenticated set to True own identity now the idea is that as said earlier we can have or the result of authentication is either a cookie or it is a Json web token now the cool thing about authentication and asp.net core is that the moment that the request has a cookie or it has a Json web token asp.net core automatically validates it and it places all the information from that cookie or from the Json web token in this HTTP context user property and if we go more here we see that in this user we have this claims and here you would see a list of all the claims that we have on the on the specific Json web token if you go in this user identity which contains the identity of the user itself you can once again get the claims but here you get a lot of other information about the roles if the user has some rules you get this property is authenticated to true or to false if the if the request is not authenticated but the core idea is here that whenever a request comes in asp.net core provides you this information about the authentication of the user and then you can simply reuse this to Define if user should have access to the end point that he or she intended to call or not so now we know exactly how asp.net core gets information about the authenticated user and how it provides this information to us so the next step would be to get this information and based on this information to Define if that specific user is authorized to perform a certain action in our application or not so let's implement this in our very simple API now let's go to our application and Define exactly on which endpoints what Excellence users are able to perform and to Showcase you this we move over to this next controller now this is a cars controller we presumably want to create an API for a car rental agency and here to this controller we can see the different cars and we can also create new cars we want to make sure that only authenticated users are authorized to access this specific endpoints so to achieve this the only thing that we need to do is we need to decorate the entire controller with this authorized attribute and while we do this it will automatically basically instruct that only users that are authenticated will be able to access any of the actions that are in this controller so let me run the application again let me here change the endpoint it should be cars it would be get and once again I don't have any authorization header so if I send the request right now I will receive this 401 unauthorized because I need a token I need to be authenticated to be able to access these endpoint so if I just add this authorization header and if I send a request again this time you see that I get all the information back however when it comes to this car controller we have also this post method which is a Creator car now regular user shouldn't be able to create cars probably only admins of these applications or editors might be able to create cars in our system so that's why on this specific endpoint for create we would like to enforce a further authorization constraint and that should be that only an administrator would be able to create a car to achieve this we will also decorate this specific action with this authorized attribute and in the authorized attribute we also have the option to specify a role or several roles that have access to this endpoint and this type of authorized attributes are cumulative so it means that first it is applied this one like the user needs to be authenticated obviously but then if a request comes in for this specific endpoint it will also enforce that the user has the administrator role so let me run again the application and I want to make this to be a post right now it should be on the car's endpoint if you go to the body you'll see that I have already prepared our body here and let's go back to the headers and let's click Ascend now we receive this 403 Forbidden and the reason why we did this is because here in this authentication or in this authorization token we don't have the administrator role it is just a regular token that doesn't have any further information so I'll come back here to my magic notepad and I have saved here the token that also contains the administrator role so let me just go here and I would just replace this token that I had earlier with the new token that should contain also the administrator role and now if I make a request I'll get these two one created now let me go to this rentals controller and the core concept of this rentals controller is that when I make a post request this endpoint I am able to just rent a car so I presumably just provide a car ID here and then there will be some logic that will make me rent the car however I'm not interested right now in the logic I'm interested in the authorization part the thing here is that we want to have have this requirement that only users that are above 18 years old will be able to get a car rented now if for the roles we could very easily in the authorize automobile just specify a role and then asp.net core did automatically everything for us for this very custom requirements that are let's say business rule or business specific we need to Define our own ways and requirements and how we should handle them unfortunately asp.net core provides us with a very simple mechanism to add our custom logic to this authorization mechanism and this mechanism implies that we can create our own requirements so I will create a class and I will name this class minimum age requirement and to make this class be an authorization requirement what we can do here is just simply inherit this eye authorization requirement now in our case we would like to be able to custom register after the age or the minimum age when we just register this policy or a policy so to do that what we'll do here is we'll just set the property with the minimum age and we'll take in the Constructor an integer that will represent the minimum age now that we have defined the requirement the next step is we need to define a Handler that will be able to handle this specific requirement and Define if the user is authorized to perform an action or not so let me create a new class here and I will name this class minimum age Handler and to make this class an authorization Handler we can simply inherit this authorization Handler class which is also a generic one and in which we will specify the requirement which we want to handle through this Handler obviously we'll just need to implement here this Missing Method as part of the contract of the after class and this would be the handle requirement async and here comes the part where we Implement our own logic here in this authorization Handler context you also get access to the HTTP context that we have logged into earlier so basically you can just really create your own logic based on all that information that you have there in the HP context in the HP context user and Define if the user is authenticated or it if the user is authorized or not in our case the logic will be very simple we just use the context user and claims and we look for a claim with the type age and then we parse that age and if it is greater than or equal to the minimum age requirement then we have this constant succeed this is how we notify sp.net core that hey this Handler has exceeded the user is authorized and then we return this task completely task as the next step we need to go back here and we need to actually register a service a Singleton one in which we will say that hey I I want to register an authorization Handler and the authorization Handler should be this minimum age Handler through these mechanisms we have registered our own Handler to this entire authorization thing in asp.net core now last but not least the one thing that we still need to do we need to add a policy to asp.net characterization to actually instruct it that it should look into our requirement and that the requirement should actually successfully pass so to do this we will have this Builder Services add authorization and we had this earlier but here I just wanted to add some new options to it so I'll just remove it from here for now and here we have options and on these options we can add policies and we can add as many policies as we need in our case we just specify a minimum age name which is a string that represents the name of the policy and then on the policy we see that requirements and add and we have here to add a new minimum age requirement environment and by the way you can once again go very granular here because on each policy you can register different requirements so it is not that you just need one requirement you can have several different requirements and in order for this policy to pass all those requirements would have to be passed successfully otherwise not now if we go back to the rentals controller one thing that we want to have is first of all we want to have an authorized here for the entire controller but then for this specific action we want to have this authorized and we can provide in a Constructor of this authorized the name of the policy that we want to impose on this specific endpoint now let me run the application and before we'll be able to make the call we know that we also need to change the authenticated user so I'll go back here to my magic notepad and then I'll get this token for the correct minimum age so if I go back to post my and I can simply change the token and then if I click send you see that I get this response back that is rented however if I get the other token where I have the wrong minimum age and click Send you'll see that we get once again 403 Forbidden because in our case we don't meet this minimum age requirement when it comes to authorization in asp.net core that's mostly it this is the core and as you saw it's really not difficult to understand it's just the ability to Define very granularly which user is allowed to perform an action or not and we can do all this based on the information that asp.net core already provides to us in each request and trust me what I have showed you in this video will cover probably around 80 percent of all your authorization AIDS needs in your asp.net core apps don't forget to like this video If you enjoyed it and subscribe to the channel if you're for the first time here and if you have any question we just want to get in touch with me head over to the comment section and just drop a line and I would be more than happy to get in touch with you this being said thank you very much for watching and until the next time I wish you the very best
Info
Channel: Codewrinkles
Views: 2,485
Rating: undefined out of 5
Keywords:
Id: OcCKmodXW-Q
Channel Id: undefined
Length: 19min 12sec (1152 seconds)
Published: Tue May 30 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.