Robert
Robert

Reputation: 4406

Passing parameters and Custom Attributes

I am not sure where to go with my issue. I want to create a custom authorization attribute for checking roles and permissions. Our permissions are not your standard this role has these permissions but more of a each role can have some permissions but not others.

I have overridden the AuthorizeCore method in the AuthorizeAttribute class:

 internal class RoleAttribute : AuthorizeAttribute
{
    private readonly IUserRepository _userRepository;
    private readonly IPermissionRepository _permissionRepository;

    public RoleAttribute(IUserRepository userRepository, IPermissionRepository permissionRepository)
    {
        _userRepository = userRepository;
        _permissionRepository = permissionRepository;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        User user = _userRepository.GetUsers();
        Permission permission = _permissionRepository.GetPermissions();
        return user.Permissions.Where(x => x.Id == permission.Id).Any();
    }
}

So that when I implement the attribute:

         private static IUserRepository _userRepository;
    private static IPermissionRepository _permissionRepository;

    public TopNavigationController(IUserRepository userRepository, IPermissionRepository permissionRepository)
    {
        _userRepository = userRepository;
        _permissionRepository = permissionRepository;
    }

    [Role(_userRepository, _permissionRepository)]
    public ActionResult MethodThatHasStuff()
    {
         //Do stuff return stuff if user has the permissions
    }

I cannot dependency inject into the overridden method because I cannot then pass the injections into the attribute.

I realize this is not a great way to approach the problem but until we can work something out with our customer that moves us towards better practices I need to develop accordingly.

My main question is: Is there a better way to create a custom authorization filter that would allow this type of behavior?

Upvotes: 0

Views: 1053

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239440

If you have the idea that just because you instantiate the repositories in the controller, that the same instances will be used for each request, you're mistaken. The controller will be instantiated each time. As a result, you're not saving yourself much by not simply just instantiating the repos in the attribute. Given the limitations of using an attribute, there's really no better way to give it access to the dependencies, and using statics on a controller is a hugely bad idea.

Upvotes: 1

Related Questions