Authorizing Resources
In this lesson, we will learn how roles and policies based on claims protect access to resources.
Access to resources can be protected either with data annotations or by checking the user claims with utility methods and interfaces. In the simplest cases, access can be based just on user roles, while more complex cases might require the definition of policies based on claims’ values. In this lesson, we will learn all these techniques, and how to define claims policies.
Protecting resources
Access to resources can be protected with three strategies:
-
Is the user authenticated? This is easily verified either with the
[Authorize]
attribute or by checking theUser.Identity.IsAuthenticated
property of theUser
property that is available in controllers, views, and in theHttpContext
instance that serves the request. The usage of theAuthorizeAttribute
will be explained in the next section of this lesson. -
The user has the required roles or not. It is worth recalling that roles are values of claims of type
ClaimType.Role
. Similar constraints are easily verified by listing all required role names, separated by commas, in theRoles
property of theAuthorizeAttribute
:[Authorize(Roles="role1,role2,...")]
. It is also possible to check theUser.IsInRole({role name})
method for each of the required roles. -
The user claims satisfy a generic policy. Policies may involve any kind of constraint on claims. They are assigned names and can be defined in various ways that we will describe throughout this lesson. A policy can be checked by assigning the policy name to the
Policy
property of theAuthorizeAttribute
:[Authorize(Policy="MyPolicy")]
. Checking a policy manually in the code requires the injection of theIAuthorizationService
and the call of itsawait IAuthorizationService.AuthorizeAsync(User, "policyName")
asynchronous method, on the current user and on the policy name. This method returns true if the policy is satisfied.
The next two sections explain how to use the AuthorizeAttribute
and check authorization in the code.
Where to place the AuthorizeAttribute
The AuthorizeAttribute
can be placed either on controllers, in which case their constraints apply to all action methods or on specific action methods:
Get hands-on with 1400+ tech skills courses.