Search code examples
c#asp.net-corerazor

How can I secure Controllers in a Razor Class Library


I have developed some Admin functionality (EF logic, Controller, and Razor UI for Audit Logs actually) that I've packaged into a Razor Class Library (RCL) and created a NuGet package. I want this functionality available to users of the package, but I want to allow them to control the access security. I would usually decorate the Controller with an Authorize Attribute, something like:

[Area("MyAuditLogPackage")]
[Authorize(Roles = "Admin")]
public class AuditLogController : Controller
...

But I don't want to presume the client's security policy and Audit Logs are sensitive data.

They could derive their own controller from mine, but the original Route would still be in their default Area Mappings.

How can I give full control of this over to the package clients?


Solution

  • Rather than authorizing by Role, you could require that people using your code create custom security policies that are defined on startup. This would result in something like

    [Area("MyAuditLogPackage")]
    [Authorize(Policy= "AuditControllerPolicy")]
    public class AuditLogController : Controller
    ...
    

    The policy approach is extremely flexible so the policy might be a requirement that a user be in role Admin. It could also require other claims be present in the token, including custom claims. Check out Policy-based Authorization in Asp.Net Core.

    This approach gives a user of your NuGet package complete flexibility, but many might find it burdensome. You might want to canvas a few to get their opinion first.