I know in controllers, you can write [Authorize("policyName")]
without an issue, but is there any way to use a policy in a view? I'd rather not use User.IsInRole(...)
every single time I want to authorize some HTML.
Edit:
Here's some code
Startup.cs -- Policy Declaration
services.AddAuthorization(options => { options.AddPolicy("testPolicy", policy => { policy.RequireAuthenticatedUser() .RequireRole("RoleOne", "RoleTwo", "RoleThree") .RequireClaim(ClaimTypes.Email); }); });
Admin Controller
[Authorize("testPolicy")] public class AdminController : Controller { public IActionResult Index() { return View(); } }
Navbar HTML
<div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a asp-controller="Home" asp-action="Index">Home</a></li> <!-- I want to implement my policy here. --> @if (User.IsInRole("...")) { <li><a asp-controller="Admin" asp-action="Index">Admin</a></li> } </ul> @await Html.PartialAsync("_LoginPartial") </div> </div>
Authorization in MVC is controlled through the AuthorizeAttribute attribute and its various parameters. At its simplest applying the AuthorizeAttribute attribute to a controller or action limits access to the controller or action to any authenticated user.
Authorization Policy The user must satisfy all the requirements. We Add the policy using the AddAuthorization method in the ConfigureServices of the startup class. options. AddPolicy("AdminOnly", policy => policy.
Role-Based Authorization in ASP.NET Core You can specify what roles are authorized to access a specific resource by using the [Authorize] attribute. You can even declare them in such a way that the authorization evaluates at the controller level, action level, or even at a global level. Let's take Slack as an example.
I ended up creating a tag helper to conditionally hide the element it's associated with.
[HtmlTargetElement(Attributes = "policy")] public class PolicyTagHelper : TagHelper { private readonly IAuthorizationService _authService; private readonly ClaimsPrincipal _principal; public PolicyTagHelper(IAuthorizationService authService, IHttpContextAccessor httpContextAccessor) { _authService = authService; _principal = httpContextAccessor.HttpContext.User; } public string Policy { get; set; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { // if (!await _authService.AuthorizeAsync(_principal, Policy)) ASP.NET Core 1.x if (!(await _authService.AuthorizeAsync(_principal, Policy)).Succeeded) output.SuppressOutput(); } }
Usage
<li policy="testPolicy"><a asp-controller="Admin" asp-action="Index">Admin</a></li>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With