text
stringlengths
0
13.4k
see a list of all users registered for the application.
As an extra challenge, try adding more administration features to
this page. For example, you could add a button that gives an
administrator the ability to delete a user account.
Check for authorization in a view
93
Authorization with roles
The [Authorize] attribute makes it easy to perform an authorization
check in a controller or action method, but what if you need to check
authorization in a view? For example, it would be nice to display a
"Manage users" link in the navigation bar if the logged-in user is an
administrator.
You can inject the UserManager directly into a view to do these types of
authorization checks. To keep your views clean and organized, create a
new partial view that will add an item to the navbar in the layout:
Views/Shared/_AdminActionsPartial.cshtml
@using Microsoft.AspNetCore.Identity
@using AspNetCoreTodo.Models
@inject SignInManager<ApplicationUser> signInManager
@inject UserManager<ApplicationUser> userManager
@if (signInManager.IsSignedIn(User))
{
var currentUser = await UserManager.GetUserAsync(User);
var isAdmin = currentUser != null
&& await userManager.IsInRoleAsync(
currentUser,
Constants.AdministratorRole);
if (isAdmin)
{
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-controller="ManageUsers"
asp-action="Index">
Manage Users
</a>
</li>
</ul>
}
}
94
Authorization with roles
It's conventional to name shared partial views starting with an _
underscore, but it's not required.
This partial view first uses the SignInManager to quickly determine
whether the user is logged in. If they aren't, the rest of the view code can
be skipped. If there is a logged-in user, the UserManager is used to look
up their details and perform an authorization check with
IsInRoleAsync() . If all checks succeed and the user is an adminstrator, a
Manage users link is added to the navbar.
To include this partial in the main layout, edit _Layout.cshtml and add it