DynamicAuthorization.Mvc.Core by Mohsen Esmailpour

<PackageReference Include="DynamicAuthorization.Mvc.Core" Version="1.0.3" />

 MvcControllerDiscovery

using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Infrastructure; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace DynamicAuthorization.Mvc.Core { public class MvcControllerDiscovery : IMvcControllerDiscovery { private List<MvcControllerInfo> _mvcControllers; private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider; public MvcControllerDiscovery(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) { _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; } public IEnumerable<MvcControllerInfo> GetControllers() { if (_mvcControllers != null) return _mvcControllers; _mvcControllers = new List<MvcControllerInfo>(); foreach (IGrouping<string, ControllerActionDescriptor> item in (from descriptor in _actionDescriptorCollectionProvider.ActionDescriptors.Items.OfType<ControllerActionDescriptor>() select (descriptor) into descriptor group descriptor by descriptor.ControllerTypeInfo.FullName).ToList()) { if (item.Any()) { ControllerActionDescriptor controllerActionDescriptor = item.First(); TypeInfo controllerTypeInfo = controllerActionDescriptor.ControllerTypeInfo; MvcControllerInfo mvcControllerInfo = new MvcControllerInfo { AreaName = controllerTypeInfo.GetCustomAttribute<AreaAttribute>()?.RouteValue, DisplayName = controllerTypeInfo.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName, Name = controllerActionDescriptor.ControllerName }; List<MvcActionInfo> list = new List<MvcActionInfo>(); foreach (ControllerActionDescriptor item2 in from a in item group a by a.ActionName into g select g.First()) { MethodInfo methodInfo = item2.MethodInfo; if (IsProtectedAction(controllerTypeInfo, methodInfo)) list.Add(new MvcActionInfo { ControllerId = mvcControllerInfo.Id, Name = item2.ActionName, DisplayName = methodInfo.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName }); } if (list.Any()) { mvcControllerInfo.Actions = list; _mvcControllers.Add(mvcControllerInfo); } } } return _mvcControllers; } private static bool IsProtectedAction(MemberInfo controllerTypeInfo, MemberInfo actionMethodInfo) { if (actionMethodInfo.GetCustomAttribute<AllowAnonymousAttribute>(true) != null) return false; if (controllerTypeInfo.GetCustomAttribute<AuthorizeAttribute>(true) != null) return true; if (actionMethodInfo.GetCustomAttribute<AuthorizeAttribute>(true) != null) return true; return false; } } }