2

I am using asp.net core mvc. Next to default authentification I have added very specific authorization which is done by using ResultFilterAttribute attribute.

In future, to make sure that developers are going to specify permissions for each controller method I would like to check if the attribute is set for method, before action is executed.

Can it be done in MVC middleware. Or maybe there is better approach?

Tseng
  • 61,549
  • 15
  • 193
  • 205
Brivvirs
  • 2,461
  • 3
  • 18
  • 31
  • Which filter type is used? I.e. which filter interface (like `IActionFilter`) you implemented? This question is probably a duplicate of https://stackoverflow.com/questions/44199347/checking-for-an-attribute-in-an-action-filter – Ilya Chumakov May 29 '17 at 12:58
  • 1
    Maybe it would be better to overwrite the `ControllerFactory`. I am not sure, if you have an MVC Context in a custom middleware. – Christian Gollhardt May 29 '17 at 14:03

1 Answers1

2

Thanks to Christian for mentioning ControllerFactory. It was right approach in my case.

 public class MyControllerFactory : DefaultControllerFactory
    {
        public MyControllerFactory (IControllerActivator controllerActivator, IEnumerable<IControllerPropertyActivator> propertyActivators)
            : base(controllerActivator, propertyActivators)
        {

        }

        public override object CreateController(ControllerContext context)
        {
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
                var isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                    .Any(a => a.GetType().Equals(typeof(PermissionFilterAttribute)));
                if (!isDefined)
                {
                    throw new NotImplementedException();
                }

            return base.CreateController(context);
        }
    }

At at Startup.cs need to tell mvc to use MyControllerFactory when resolving IControllerFactory interface.

services.AddSingleton<IControllerFactory, MyControllerFactory>();

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
Brivvirs
  • 2,461
  • 3
  • 18
  • 31