Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
A developer often wants to show, hide, or otherwise modify a UI based on the current user identity. Access the authorization service within MVC views via dependency injection. To inject the authorization service (IAuthorizationService) into a Razor view, use the @inject directive:
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthService
To inject the authorization service into every view, place the @inject directive in the Views/_ViewImports.cshtml file. For more information, see Dependency injection into views in ASP.NET Core.
Use the injected authorization service to invoke IAuthorizationService.AuthorizeAsync in exactly the same way an app would check authorization during resource-based authorization:
@if ((await AuthService.AuthorizeAsync(User, "PolicyName")).Succeeded)
{
<p>This paragraph is displayed because you fulfilled PolicyName.</p>
}
In some cases, the resource is the view model. Invoke AuthorizeAsync in exactly the same way the app would check authorization during resource-based authorization. The model is passed as a resource for the policy's evaluation:
@if ((await AuthService.AuthorizeAsync(User, Model, Operations.Edit)).Succeeded)
{
<p><a class="btn btn-default" role="button"
href="@Url.Action("Edit", "Document", new { id = Model.Id })">Edit</a></p>
}
Warning
Don't rely on toggling the visibility of the app's UI elements as the sole authorization check. Hiding a UI element may not completely prevent access to its associated controller action. For example, consider the button in the preceding code snippet. A user can invoke the Edit action method if they know the relative resource URL is /Document/Edit/1. For this reason, the Edit action method should perform its own authorization check.
ASP.NET Core