ASP. NET Web API authentication and authorization

Source: Internet
Author: User

English Original address: Http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

This article is the content that the author understands and translates.

This article includes two parts: Authentication and authorization.

    • Authentication is used to determine the identity of a user. For example, Alice uses her username and password to log on to the system, and the server uses her username and password to determine her identity.
    • Authorization is the determination of whether a user is allowed to perform an action. For example, Alice has permission to obtain a resource, but cannot create a resource.

Identity verification

The Web API has two ways of authenticating: Authentication in the host program and authentication using HTTP Message handlers.

If your Web API is running in IIS, the authenticator is HTTP Modules, you can use the built-in ASP. NET authentication module for authentication, or you can write an authentication module yourself to complete custom authentication.

When authenticating in the host program, the host program creates a principal object that implements the IPrincipal interface, which is used to represent the security context in which the current code runs. The host attaches the principal to the current process by setting Thread.CurrentPrincipal . The principal contains an Identity object that associates user information, and if the user validates the pass, theidentity.isauthenticated property returns True, and for anonymous requests, isauthenticated returns false. For more information on principals, see Role-based Security.

Using HTTP Message handlers for authentication

You can create authentication logic in the HTTP message handler instead of using the host authentication mechanism, in which the message handler validates the HTTP request and sets the principal.

When should I use HTTP Message handler for authentication? Here is a reference to this:

    • An HTTP module observes all requests through the ASP. A message handler only observes Web API requests that are routed.
    • You can set a message Handler for each route, which facilitates special authentication schemes for special routes.
    • The HTTP module is specific to IIS, and Message handler is not host-independent, so you can use it both in web-hosting and self-hosting.
    • HTTP module participates in IIS login, audit and other processing.
    • The HTTP module executes earlier in the pipeline and if you use message handler for authentication, principal is not ready before handler executes. In addition, after response leaves the message handler, principal is restored to the previous principal.

In summary, if you don't need to support self-hosting,http module back to a better choice. If you need to support self-hosting, consider using the message handler.

Set Principal

If your program has completed some custom authentication logic, then you must set the principal of Love two places:

    • Thread.CurrentPrincipal. This attribute is in the. The standard way to set thread principal in net.
    • HttpContext.Current.User. This property is dedicated to ASP.

The following code shows how to set the principal:

private void Setprincipal (IPrincipal principal) {    Thread.CurrentPrincipal = principal;    if (httpcontext.current! = null)    {        HttpContext.Current.User = principal;    }}

For web-hosting, you have to principal the index finger in these two places, otherwise the security context may become inconsistent. Is null for self-hosting,httpcontext.current. To make sure your code is not related to the host, check the httpcontext.current before assigning it, just like the code above.

Authorized

Authorization occurs at the back of the pipeline, closer to the controller. It allows you to perform more granular operations on authorized access to resources.

    • Authorization Filters runs before the controller action. If the request is not authorized, filter returns an incorrect response,action that is not called.
    • Inside the controller action, you can access the current principal through the Apicontroller.user property. For example, you might want to filter a list of resources based on the user, returning only the resources that belong to that user.

Using the [authorize] property

The Web API provides a built-in authorization filter: Authorizeattribute. This filter checks whether the user is authorized and, if not, returns the HTTP status code 401 (unauthorized) and does not invoke action.

You can add a filter to the globally, or controller level, or action level.

Globally: To add a constraint for each Web API request, add Authorizeattribute to the global filter list.

public static void Register (Httpconfiguration config) {    config. Filters.add (New Authorizeattribute ());}

Controller: To constrain access to a particular controller, add Authorizeattribute on the controller.

[Authorize]public class valuescontroller:apicontroller{public    httpresponsemessage Get (int id) {...}    Public Httpresponsemessage Post () {...}}

Action: To constrain access to a special action, add Authorizeattribute on the action.

public class valuescontroller:apicontroller{Public    httpresponsemessage Get () {...}    Require Authorization for a specific action.    [Authorize]    Public Httpresponsemessage Post () {...}}

In addition, you can constrain the access of a controller while allowing anonymous access to the special action, which requires the use of the [AllowAnonymous] property. In the following example, the Post method is constrained, and the Get method allows anonymous access:

[Authorize]public class valuescontroller:apicontroller{    [allowanonymous] public    httpresponsemessage Get () { ... }    Public Httpresponsemessage Post () {...}}

In the example above, the filter allows any authenticated user to access the constrained method, and only anonymous users are denied.

You can also restrict access to some special users or special roles:

Restrict by user:[authorize (Users = "Alice,bob")]public class valuescontroller:apicontroller{}//Restrict by Role:[au Thorize (Roles = "Administrators")]public class valuescontroller:apicontroller{}

Note: The Authorizeattribute filter in the Web API is in the namespace System.Web.Http, and there is a similar filter in the MVC controller that is defined in the SYSTEM.WEB.MVC and cannot be used in a compatible environment.

Custom Authorization Filters

A custom authorization filter derives from several types:

    • Authorizeattribute. Extend this class to complete authorization logic based on the current user and role.
    • Authorizationfilterattribute. Extending this class to complete the authorization logic for synchronization must be based on the current user and role.
    • Iauthorizationfilter. Implement this interface to complete the asynchronous authorization logic. For example, if your authorization logic uses asynchronous IO or network calls (if your authorization logic is cpu-bound, then simply derive from Authorizationfilterattribute, as you don't need to write an async method)

The following diagram shows the class hierarchy for the Authorizeattribute class.

The following image shows the class level of the Authorizeattribute:

Authorizing in controller action

Sometimes you may allow a request to go on, but change its behavior according to principal. For example, the information you return will depend on changes in the user role. In the controller's method, you can get the current principal through the Apicontroller.user property.

Public Httpresponsemessage Get () {    if (user.isinrole ("Administrators"))    {        //...    }}

Ps. Reluctantly translated the content of this article, as a study notes it.

ASP. NET Web API authentication and authorization

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.