Reputation: 822
Is there any way to get all authorized endpoints of a .net core API? At the moment i managed to get all routes:
[HttpGet("routes")]
public IActionResult GetRoutes() {
var routes = _provider.ActionDescriptors.Items.Select(x => new {
Action = x.RouteValues["Action"],
Controller = x.RouteValues["Controller"],
Name = x.AttributeRouteInfo.Name,
Template = x.AttributeRouteInfo.Template
}).ToList();
return Ok(routes);
}
But is there any way to know which route has [Authorized] annotation?
Thanks in advance
Upvotes: 0
Views: 537
Reputation: 11564
Here is my implementation to find secured controllers and actions:
public class MvcControllerDiscovery : IMvcControllerDiscovery
{
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
public MvcControllerDiscovery(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
public IEnumerable<MvcControllerInfo> GetControllers()
{
var items = _actionDescriptorCollectionProvider
.ActionDescriptors.Items
.Where(descriptor => descriptor.GetType() == typeof(ControllerActionDescriptor))
.Select(descriptor => (ControllerActionDescriptor)descriptor)
.GroupBy(descriptor => descriptor.ControllerTypeInfo.FullName)
.ToList();
foreach (var actionDescriptors in items)
{
if (!actionDescriptors.Any())
continue;
var actionDescriptor = actionDescriptors.First();
var controllerTypeInfo = actionDescriptor.ControllerTypeInfo;
foreach (var descriptor in actionDescriptors.GroupBy(a => a.ActionName).Select(g => g.First()))
{
var methodInfo = descriptor.MethodInfo;
if (IsProtectedAction(controllerTypeInfo, methodInfo))
{
}
}
}
}
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;
}
}
Full source code on github.
Upvotes: 1