Skip to content

Instantly share code, notes, and snippets.

@DejanMilicic
Last active February 13, 2017 18: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/678b49b4465047d0a27a0335111bfd92 to your computer and use it in GitHub Desktop.
Save DejanMilicic/678b49b4465047d0a27a0335111bfd92 to your computer and use it in GitHub Desktop.
Tag Helper : required-claims
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Infrastructure.MVC
{
[HtmlTargetElement(Attributes = "required-claim")]
public class RequiredClaimsTagHelper : TagHelper
{
private readonly IHttpContextAccessor httpContextAccessor;
public RequiredClaimsTagHelper(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
[HtmlAttributeName("required-claim")]
public string RequiredClaim { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (null == httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(claim => claim.Type == this.RequiredClaim))
{
output.SuppressOutput();
}
}
}
}
@DejanMilicic
Copy link
Author

Use it on any html element to hide it if current user does not have required claim

<a required-claim="admin" asp-controller="Home" asp-action="About">About</a>

Concerns

  1. Claim value is not checked, it can be even empty
  2. User.Identity.IsAuthenticated is not checked since it is orthogonal concept to claims - claim existence is not dependant on Authentication

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