I'm new to ASP.NET Core, and I have been trying to look for a way to implement permission-based authorization where a user has to have a certain permission to access a particular action. As I was going through Microsoft Authorization documentation, they explained how to achieve this by using a custom IAuthorizationPolicyProvider which I have understood but not yet tried it out. But my question is, Is there any problem or is it okay if I use a custom parameterized authorization filter to do the same?
public class HasPermissionAttribute : Attribute, IAuthorizationFilter { private readonly string permission;
public HasPermissionAttribute(string permission)
{
this.permission = permission;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if (user.HasClaim("Permission", permission))
{
context.Result = new UnauthorizedResult();
}
}
}
And use the filter as seen below
public class HomeController : Controller {
[HasPermission("User_Edit")
public IActionResult EditUser()
{
var user = HttpContext.User;
return View(user);
}
}
From the code above, what if I add some custom claims of type "Permission" then use them to authorization a user.
Is there any drawback to doing it this way or should I stick to creating a custom IAuthorizationPolicyProvider?
I am a beginner, and I think this way is too easy and that kinda makes me think that it's not really the right way of achieving what I want to achieve. Any feedback will be appreciated. Thanks