What is Authorization?
In Core, authorization is the process of controlling access to application resources. It determines which users or groups of users can access certain resources or perform certain actions. Authorization is often used in conjunction with authentication, which is the process of verifying a user's identity. Authorization and authentication are independent of each other, but authorization requires an authentication mechanism. Authentication is the process of determining a user's identity. Authentication creates one or more identifiers for the current user.
Type of authorization
- simple authorization
- Role-based authorization
- Policy-based authorization
Simple Authorization
Configuring Authentication Middleware
// authentication (the core source code is the AuthenticationMiddleware middleware)
();
//authorization
().
authorize the use of sth.
Authorization in Core is done through the[Authorize] property and its various parameter controls. In its most basic form, the [Authorize] attribute is controlled by applying the
[Authorize]` property, which can be restricted to allow only authenticated users to access the component.
To implement the default authorization behavior, you can simply use the [Authorize] attribute on controllers or operations that you need to restrict access to without specifying any particular role or policy. This way, only authenticated users can access these resources.
[Authorize]
public IActionResult Info()
{
return View();
}
-
[AllowAnonymous]
Bypassing authorization statements. The authorization statement can be bypassed if the[AllowAnonymous]
sum up to a certain[Authorize]
attribute is used in combination, the system ignores the[Authorize]
attribute. For example, if you apply the[AllowAnonymous]
:- Properties from the same controller will be ignored
[Authorize]
or any authorization requirements for the method of operation on the controller. - The authentication middleware will not short-circuit, but does not need to succeed.
- Properties from the same controller will be ignored
Authorization Principle
/dotnet/aspnetcore/blob/main/src/Security/Authorization/Core/src/
/dotnet/aspnetcore/blob/main/src/Security/Authorization/Policy/src/
static AuthenticateResult DefaultAuthenticateResult(HttpContext context)
{
return (?.Identity?.IsAuthenticated ?? false)
? (new AuthenticationTicket(, ""))
: ();
}
Role-based authorization
When creating a logo, it may belong to one or more roles. For example, Tracy may belong toAdmin
cap (a poem)User
The role of Scott only belongs toUser
Roles. How these roles are created and managed depends on the backing store for the authorization process.
Configuring Authentication Middleware
// authentication (the core source code is the AuthenticationMiddleware middleware)
();
//authorization
().
authorize the use of sth.
Only if the user is a member of theadmin
maybeuser
Accessed only when a member of the roleInfo
[Authorize(Roles ="admin,user")]
public IActionResult Info()
{
return View();
}
Authorization based on a declarative strategy
After an identity is created, it can be assigned one or more declarations issued by a trusted party. A declaration is a name-value pair that indicates what the user is, not what the user can do.
Configuration Policy
(options =>
{
("AdminPolicy", policyBuilder =>
{
("admin");
});
});
authorize the use of sth.
[Authorize(Policy = "AdminPolicy")]
public IActionResult Info()
{
return View();
}
Authorization based on custom policies
At the bottom.Role-based authorizationcap (a poem)Authorization based on declarationsAll use requirements, requirement handlers, and pre-configured policies. These building blocks support expressions for authorization evaluation in code. The result is a richer, reusable and testable authorization structure.
Configuration Policy
(options =>
{
("PermissionPolicy", policyBuilder =>
{
(new PermissionRequirement());
});
});
Configuring the Authorization Handler
IAuthorizationRequirement is a methodless tagging service and a mechanism for tracking the success of authorizations.
everyoneIAuthorizationHandler Responsible for checking that requirements are met
/// <summary>
/// IAuthorizationRequirementinterface identification
/// </summary>
public class PermissionRequirement : IAuthorizationRequirement
{
}
public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
{
private readonly IHttpContextAccessor _accessor;
public PermissionHandler(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
if ( == null || ?.Identity?.IsAuthenticated == false)
{
//await _accessor.(new { code = 401, message = "Please log in first" });
();
}
else
{
var role = (i => == ).FirstOrDefault();
//database search
if (role != null && == "admin")
{
(requirement);
}
else
{
();
}
}
await ;
}
}
authorize the use of sth.
[Authorize(Policy= "TestPolicy")]
public IActionResult Info()
{
return View();
}
Customized Response
The application can be registeredIAuthorizationMiddlewareResultHandlerto customize theAuthorizationMiddleware The way the authorization results are handled. The application can set theIAuthorizationMiddlewareResultHandler
Used for:
- Returns a customized response.
- Enhance the default interrogation or disable the response.
public class PermissionResultHandler : IAuthorizationMiddlewareResultHandler
{
public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
{
//var endPoint = ();
//var controllerActionDescriptor = (ControllerActionDescriptor)
// .ToList().FirstOrDefault(d => d is ControllerActionDescriptor);
//var controllerName = ;
//var actionName = ;
if (!)
{
= (int);
await ("{\"data\":{\"succeeded\":false,\"code\":401,\"message\":\"Login has expired,Please log in again\"}}");
return;
}
if (!)
{
await ("{\"data\":{\"succeeded\":false,\"code\":403,\"message\":\"You do not have permission to operate\"}}");
return;
}
await next(context);
}
}