Custom authorization in ASP.NET as a filter or in a controller constructor?

In my ASP.NET API, I want to restrict access to topics from the user role. The general way to do this is to extend the AuthorizeAttribute ( example , example ) and then sprinkle my controllers with your custom attribute (eg [AuthorizeUser]).

Another way to do this is to add a function to the controller constructor. The constructor is required anyway because I am using dependency injection.

Here is the code:

public class MyController: ApiController
{
    private IUnitOfWork unitOfWork;
    private IAccountUtils accountUtils;

    // Constructor
    public MyController(
        IUnitOfWork unitOfWork, 
        IAccountUtils accountUtils)
    {
        this.unitOfWork = unitOfWork;
        this.accountUtils = accountUtils;

        // Restrict access to 'User' role
        accountUtils.ThrowExceptionIfUserNotInRole(User.Identity, "User");
    }

    // More code
}

      

Since there are countless tutorials and examples of how to use a filter to authenticate users, I assumed this is the best way. However, when I stepped through my code in the debugger, I found that the constructor method runs before the filter.

To optimize the code, it makes sense to break as soon as possible if the user does not have access to the controller. If I am not mistaken then it should be more efficient to do authorization in constructors rather than filter. Am I correct or am I missing something here?

+3


source to share


1 answer


Your main concern seems to be to optimize your code, and you've correctly noticed that the controller constructor runs before the authorization filter. But the difference in performance between the two is extremely small and shouldn't affect your service.

While throwing from a constructor might work, it is not the most elegant solution because it requires authorization in the code, not declaratively with an attribute. It also forces you to mix object creation logic with authorization logic, which is not as clean.



So I would recommend just sticking to using an authorization filter for this.

+1


source







All Articles