Authentication (Certified)
Authentication in WEBAPI can use either Httpmodel or HTTP message handler, which can be used to refer to the basis:
- A httpmodel can detect all requests in the ASP. A message handler can only detect requests that are routed to this WEBAPI
- You can pre-set the message handlers to allow a specific route to use the specified authentication scheme
- Http module can only be used in IIS, Message Hans can be used in any ost-agnostic environment (web-hosting and Self-hosting)
- HTTP module participates in IIS login, audit and other processes
- The HTTP module is executed at the beginning of the pipeline event, and is only assigned if the message Handler,principal is used until handler executes
Usually. If you do not need to run in the self-hosting environment, the HTTP model is a good choice, conversely, you can consider the message handler.
Set Principal
If application needs to perform custom authentication logic, it needs to be set up in two places principal
- Thread.CurrentPrincipal for. NET
- HttpContext.Current.User for ASP.
Private void Setprincipal (IPrincipal principal) { = principal; if NULL { = principal; }}
Authorization (Authorized)
Authorization is executed near the controller in order to have more opportunities for fine-grained control over access to resources.
- Authorization filters is executed before the controller action, if no authorization action is called
- Within the controller action, the current principal can be obtained from the apicontroller.user
Use[Authorize] Properties
Authorize can be applied to globally, controller, and action levels. Priority: action>controller>globally
[Authorize] Public class valuescontroller:apicontroller{ [allowanonymous]// allow anonymous access to public httpresponsemessage Get () {...} // authorized users to access Public httpresponsemessage Post () {...}}
You can also control the permissions required to access the action
[Authorize (users="alice,bob")] Public class valuescontroller:apicontroller{} // Restrict by role: [Authorize (roles="Administrators")] Public class valuescontroller:apicontroller{}
Custom Authorization Filters
Custom authorization filters can be used by continuing Authorizeattribute or authorizationfilterattribute or Iauthorizationfilter is implemented if the CPU-intensive authentication logic should be used in a synchronous manner, and if it is IO-intensive, the Async method should be used.
Authorizeattribute's Hierarchical relationship:
WEBAPI2 official website Study Record---authentication and authorization