.Net Core Authorization on data displaying on view

309 Views Asked by At

I am trying add an authorization logic to my .net core web based application to allow only the author(recorded in each database record as username) allow for edit/delete kind of action, others only can read.

I did some googling, seems Resource based authorization may suit my requirements: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-2.1&tabs=aspnetcore2x

Not sure if I need to write a lot of handlers to implement the logic as shown in this example? https://learn.microsoft.com/en-us/aspnet/core/security/authorization/secure-data?view=aspnetcore-2.1

My understanding, the logic is like:

If current login user == the created by user in database record
    Display edit/delete link.
    Allow access the edit/delete action method in Controller.
Else
    Access is denied.

Should I follow what the sample code's way or write my own authorization class? And if it is simpler to write my own authorization logic class, how could I invoke the logic as attribute above edit/delete action method in the controller?

Thank you.

1

There are 1 best solutions below

2
On

Not sure if I need to write a lot of handlers to implement the logic as shown in this example?

There is no need, you could define one PermissionHandler which will check the user permission in HandleAsync.

how could I invoke the logic as attribute above edit/delete action method in the controller?

For invoking as attribute, you could try like

[Authorize(Policy = "Read")]
[HttpPost("delete")]
public IActionResult Delete([FromBody]Item item)
{
  _itemService.Delete(item.Id);
  return Ok();
}

For a complete demo, try to refer Different API functionality for different roles.