Search code examples
c#asp.net-coreentity-framework-corerole-base-authorizationresource-based-authorization

How to use resource and role based authorization on AspNet Core 3.1 with EF Core?


I'm working on a marketplace backend application with role based authorization, and I'm handling access to actions using those roles. The admins manage all products and their filtering categories while the sellers choose which one to sell, with its filter options and its price. By the way, I'm quite new to asp.net core and ef core, so forgive me if this is a simple request.

If a seller sends a put request with data like this, it can update the filter option name, but that is a action that should be available only to admins on another path/action.

Is there a simple good solution other than create specific models for each action? Something like block the update access to that resource when it's part of another one?

{
  "productId": "1",
  "options": [
    {
      "filterCategoryId": "2",
      "filterOptionId": "4",
      "filterOptionName": "Blue"
    },
    {
      "filterCategoryId": "1",
      "filterOptionId": "1",
      "filterOptionName": "XL"
    }
  ],
  "price": "123.00",
  "amount": "5"
}

Solution

  • You can use User.IsInRole("roleName") in the Action to control whether or not the filter options may be changed. For Example:

    public async Task<ActionResult>(ProductDetails p)
    {
        if(User.IsInRole("Administrator"))
        {
             //Update Filter Names
        }
    
        //do whatever else you need to...
    }