Reputation: 3
I implemented Custom Policy=Based Authorization as per https://docs.asp.net/en/latest/security/authorization/policies.html.
This ended up being successful when it was accessed via the [Authorize] in a controller. However when I attempt to use it in my view as below. I get in issue with the context.Resource being null.
I am new to mvc so any help is appreciated.
View
@if (await AuthorizationService.AuthorizeAsync(User, "IsRegisteredUser"))
{
<li><a asp-area="" asp-controller="Solution" asp-action="Index">Solutions</a></li>
}
Authorization Handler
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsRegisteredUserRequirement requirement)
{
if(context.User.Identity.IsAuthenticated)
{
var mvcContext = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
}
return Task.CompletedTask;
}
Upvotes: 0
Views: 618
Reputation: 26
In the view you can use the overload method of AuthorizeAsync with the resource parameter set with the ViewContext:
await AuthorizationService.AuthorizeAsync(User, ViewContext, "YourPolicyName");
Then in the handler you can cast the resource to ActionContext base class, from which ViewContext and AuthorizationFilterContext inherit:
var actionContext = context.Resource as Microsoft.AspNetCore.Mvc.ActionContext;
You then have access to the HttpContext, ModelState and RouteData.
Upvotes: 1