Skip to content

Instantly share code, notes, and snippets.

@DejanMilicic
Created February 26, 2017 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DejanMilicic/bcf818deece7ac4e00cfd450236c6ee7 to your computer and use it in GitHub Desktop.
Save DejanMilicic/bcf818deece7ac4e00cfd450236c6ee7 to your computer and use it in GitHub Desktop.
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;
namespace Infrastructure.MVC
{
[HtmlTargetElement("a", Attributes = ActionAttributeName)]
[HtmlTargetElement("a", Attributes = ControllerAttributeName)]
public class PolicyTagHelper : TagHelper
{
private const string ActionAttributeName = "asp-action";
private const string ControllerAttributeName = "asp-controller";
[HtmlAttributeName(ActionAttributeName)]
public string Action { get; set; }
[HtmlAttributeName(ControllerAttributeName)]
public string Controller { get; set; }
private readonly IHttpContextAccessor httpContextAccessor;
private readonly IActionDescriptorCollectionProvider adcProvider;
private readonly IAuthorizationService authService;
public PolicyTagHelper(
IHttpContextAccessor httpContextAccessor,
IActionDescriptorCollectionProvider adcProvider,
IAuthorizationService authService)
{
this.httpContextAccessor = httpContextAccessor;
this.adcProvider = adcProvider;
this.authService = authService;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (string.IsNullOrWhiteSpace(Controller)) return;
if (string.IsNullOrWhiteSpace(Action)) return;
ActionDescriptor actionDescriptor = this.adcProvider.ActionDescriptors.Items
.FirstOrDefault(x =>
(x as ControllerActionDescriptor).ControllerName == Controller
&&
(x as ControllerActionDescriptor).ActionName == Action
);
if (actionDescriptor == null) return;
var authorizeFilters = actionDescriptor.FilterDescriptors.Select(x => x.Filter).OfType<AuthorizeFilter>();
if (authorizeFilters.Any())
{
bool suppressOutput = false;
foreach(var authorizeFilter in authorizeFilters)
{
bool auth = await this.authService.AuthorizeAsync(this.httpContextAccessor.HttpContext.User, authorizeFilter.Policy);
if (!auth)
{
suppressOutput = true;
break;
}
}
if (suppressOutput) output.SuppressOutput();
}
}
}
}
@DejanMilicic
Copy link
Author

This tag helper should be registered after system tag helpers.
It will determine visibility of hyperlinks based on Authorize attribute and its policy controller or action are marked with

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