Skip to content

Instantly share code, notes, and snippets.

@sam9291
Last active June 16, 2020 07:52
Show Gist options
  • Save sam9291/dba558f417a04b1775b51b20eb0f96ab to your computer and use it in GitHub Desktop.
Save sam9291/dba558f417a04b1775b51b20eb0f96ab to your computer and use it in GitHub Desktop.
/*
Sample of the output:
[
"GET -> api/monitor/routes",
" -> api/monitor",
"POST -> someRoute/test",
"GET -> api/values",
" -> Error",
"-------- SECURED ROUTES --------",
"[Authenticated] POST -> api/values",
"[Authenticated] GET -> api/values",
"[Authenticated] GET -> api/users/current",
"[Authenticated] GET -> api/users/{userId}",
"[Administrator] PATCH -> api/users/{userId}",
"[Authenticated] GET -> api/users/roles",
"[Administrator] GET -> api/users"
]
*/
[Route("api/monitor")]
public class MonitorController : Controller
{
private readonly IActionDescriptorCollectionProvider _provider;
public MonitorController(IActionDescriptorCollectionProvider provider)
{
_provider = provider;
}
[HttpGet("routes")]
public IActionResult GetRoutes()
{
System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor> openRoutes = _provider.ActionDescriptors.Items
.Where(x => x.FilterDescriptors.All(f => f.Filter.GetType() != typeof(AuthorizeFilter)) ||
x.FilterDescriptors.Any(f => f.Filter.GetType() == typeof(AllowAnonymousFilter)));
var openRoutesDisplay = openRoutes
.Select(x => $"{x?.ActionConstraints?.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods.First()} -> {x.AttributeRouteInfo.Template}");
var roleGroupedRoutesDisplay = _provider.ActionDescriptors.Items
.Except(openRoutes)
.GroupBy(r => GetAuthorizationRole(r))
.SelectMany(g =>
g.Select(x => $"[{g.Key}] {x?.ActionConstraints?.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods.First()} -> {x.AttributeRouteInfo.Template}")
).ToArray();
return Ok(openRoutesDisplay
.Concat(new []{"-------- SECURED ROUTES --------"})
.Concat(roleGroupedRoutesDisplay));
}
public string GetAuthorizationRole(ActionDescriptor action) {
var allowedRoles = ((RolesAuthorizationRequirement)action.FilterDescriptors.Where(x => x.Filter.GetType() == typeof(AuthorizeFilter))
.SelectMany(x => ((AuthorizeFilter)x.Filter).Policy.Requirements)
.FirstOrDefault(x => x.GetType() == typeof(RolesAuthorizationRequirement)))?.AllowedRoles;
if(allowedRoles == null){
return "Authenticated";
}
return string.Join(", ", allowedRoles);
}
}
@wbhyde
Copy link

wbhyde commented Nov 24, 2018

api/monitor gets a null reference exception since I didn't have any authorized routes; however, api/monitor/routes worked well and showed my problem. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment