Implement role-based authorization ASP.NET Core Identity has a built-in concept of roles. In addition to users, ASP.NET Core Identity
stores information about different roles used by the application and keeps track of which users are
assigned to which roles. These assignments can be changed programmatically with the
RoleManager
type that updates roles in persisted storage, and the
UserManager
type that can grant or revoke roles
from users.
If you’re authenticating with JWT bearer tokens, the ASP.NET Core JWT bearer authentication
middleware will populate a user’s roles based on role claims found in the token. To limit access to an
MVC action or controller to users in specific roles, you can include a Roles parameter in the Authorize
annotation (attribute), as shown in the following code fragment:
[
Authorize
(Roles =
"Administrator, PowerUser"
)]
public class ControlPanelController : Controller
{
public ActionResult
SetTime
()
{
}
[
Authorize
(Roles =
"Administrator"
)]
public ActionResult
ShutDown
()
{
}
}
In this example, only users in the Administrator or PowerUser roles can access APIs in the
ControlPanel controller (such as executing the SetTime action). The ShutDown API is further restricted
to allow access only to users in the Administrator role.
To require a user be in multiple roles, you use multiple Authorize attributes, as shown in the following
example:
[
Authorize
(Roles =
"Administrator, PowerUser"
)]
[
Authorize
(Roles =
"RemoteEmployee "
)]
[
Authorize
(Policy =
"CustomPolicy"
)]
public ActionResult
API1
()
{
}
In this example, to call API1, a user must:
•
Be in the Administrator
or PowerUser role,
and •
Be in the RemoteEmployee role,
and
330
CHAPTER 8 | Make secure .NET Microservices and Web Applications
•
Satisfy a custom handler for CustomPolicy authorization.