Authorizing Resources
Explore how to protect resources in ASP.NET Core MVC by using the Authorize attribute, role-based checks, and custom claims policies. Learn to define policies, apply authorization on controllers, actions, and routes, and handle exceptions with AllowAnonymous. This lesson guides you through maintaining secure access through both declarative and manual authorization techniques.
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.IsAuthenticatedproperty of theUserproperty that is available in controllers, views, and in theHttpContextinstance that serves the request. The usage of theAuthorizeAttributewill 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 theRolesproperty of theAuthorizeAttribute:[Authorize(Roles="role1,role2,...")]. It is also possible to check theUser.IsInRole({role name})method for each of the ...