0

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

1 Answers1

0

The recommend way is to use policy based approach , generate the policies dynamically with a custom AuthorizationPolicyProvider using custom authorization attribute .

From this reply :

We don't want you writing custom authorize attributes. If you need to do that we've done something wrong. Instead you should be writing authorization requirements.

Similar discussion here is also for your reference .

Nan Yu
  • 21,285
  • 5
  • 39
  • 110
  • I've gone through the discussion, though the solution you/they provide is efficient and I agree with it,. but I would like to know if there are any negative effects if I do it the way I described above ( for the sake of learning and gaining a deeper understanding of this topic ) – Zack Boniphace Jul 22 '19 at 07:40
  • No obvious negative . In fact , i would say use custom attribute also effective in your scenario . But the recommend way is to use policy which suggested by asp.net core team . – Nan Yu Jul 22 '19 at 07:42