So we all are more or less familiar with authorization in ASP.Net MVC and the new policy based authorization where the most commonly used example is a policy called atLeast21
which grants access to a specific resource only to users 21 years old or older.
But what if I wanted the policy to be used for multiple ages and pass the age as a parameter like in the following example:
[Authorize("AtLeast", new { age = 21 })]
public IActionResult Index()
{
//some code here
return View();
}
[Authorize("AtLeast", new { age = 25 })]
public IActionResult Index2()
{
//some code here
return View();
}
This way I could use the same policy (AtLeast
) multiple times and won't have to create a policy for every single age I want to check.
So, of course there aren't many use cases for this if we are talking about restricting the age of a user but it definitely has many use cases if I want to say have multiple actions in a controller and one is for employees working in the company for 1 year, one is for employees working more than one year, one is for employees working more than 5 years in the company and so on and many more use cases.
Unfortunately I couldn't find much information about this in the web, this is why I am asking if this is achievable at all in ASP.Net MVC in one way or another or not?
Thanks
You have to create parameterized authorize attribute. Please look at this example here https://learn.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-2.2 It is based on the same policy you have used.