ASP. NET Web API authentication and authorization

Source: Internet
Author: User
Document directory
  • Use HTTP Message Handlers for authentication
  • Set Principal
  • Use the [Authorize] attribute
  • Custom Authorization Filters
  • Authorize in Controller Action

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

This article is what the author understands and translates.

This article consists of two parts: authentication and authorization.

  • Identity Verification 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 used to determine whether a user is allowed to perform an operation. For example, Alice has permission to obtain resources, but cannot create resources.

 

Authentication

The Web API provides two authentication methods: authentication in the Host Program and authentication using HTTP Message Handlers.

If your Web API runs in IIS, the authentication program is HTTP Modules. You can use the built-in asp.net authentication module for authentication, you can also write an authentication module to complete custom authentication.

When identity authentication is performed in the Host Program, the host program creates a principal object. The class of this object implements the IPrincipal interface to represent the security context in which the current code runs. Host settingsThread. CurrentPrincipalAttaches the subject to the current process. PrincipalIdentityObject. If the user passes the verification,Identity. IsAuthenticatedProperty returnTrueFor anonymous requests,IsAuthenticatedReturnFalse. For more information about principals, see Role-Based Security.

Use HTTP Message Handlers for authentication

You can create an authentication logic in HTTP message handler to replace the Host Authentication mechanism. In this mechanism, message handler checks Http requests and sets principal.

When should I use HTTP Message Handler for identity authentication? Here is a reference for this:

  • One HTTP Module observes all requests through the ASP. NET pipeline; one Message Handler observes only the Web API requests processed by the route.
  • You can set a Message Handler for each route, which facilitates setting special authentication schemes for special routes.
  • The HTTP Module is unique to IIS; the Message Handler has nothing to do with the host, so you can use it in both web-hosting and self-hosting.
  • The HTTP Module is used for IIS login and review.
  • The HTTP Module is executed earlier in the pipeline. If you use Message Handler for authentication, principal is not ready before handler is executed. In addition, after response leaves Message Handler, principal is restored to the previous principal.

To sum up, if you do not need to support self-hosting, HTTP Module is a better choice. If you need to support self-hosting, consider using Message Handler.

 

Set Principal

If your program has completed some custom authentication logic, you must set principal in two places:

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

The following code shows how to set principal:

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

For web-hosting, you must index the principal in the two locations, otherwise the security context may become inconsistent. For self-hosting, HttpContext. Current is null. To ensure that your code has nothing to do with the host, check HttpContext. Current before assigning a value, just like the code above.

 

Authorization

The authorization takes place after the pipeline, which is closer to the controller. It allows you to perform fine-grained operations on authorized resources.

  • Authorization filtersRun before controller Action. If the request is not authorized, the filter returns an incorrect response, and the action will not be called.
  • In the Controller Action, you can access the current principal through the ApiController. User attribute. For example, you may want to filter a resource list based on the user and return only the resources belonging to the user.

Use the [Authorize] attribute

The Web API provides a built-in authorization filter: AuthorizeAttribute. This filter checks whether the user is authorized. If not, http status code 401 (Unauthorized) is returned and no Action is called.

You can add a filter to the globally, Controller, or Action level.

Globally: to add constraints 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 restrict access to a special controller, add AuthorizeAttribute to the controller.

[Authorize]public class ValuesController : ApiController{    public HttpResponseMessage Get(int id) { ... }    public HttpResponseMessage Post() { ... }}

 

Action: to restrict access to a special Action, add AuthorizeAttribute to the Action.

public class ValuesController : ApiController{    public HttpResponseMessage Get() { ... }    // Require authorization for a specific action.    [Authorize]    public HttpResponseMessage Post() { ... }}

In addition, you can restrict access by a controller and allow anonymous access to special actions. This requires the [AllowAnonymous] attribute. In the following example, the Post method is restricted, and the Get method is allowed to be accessed anonymously:

[Authorize]public class ValuesController : ApiController{    [AllowAnonymous]    public HttpResponseMessage Get() { ... }    public HttpResponseMessage Post() { ... }}

In the preceding example, the filter allows any authenticated user to access restricted methods, and only anonymous users are denied.

You can also restrict the access of some special users or special roles:

// Restrict by user:[Authorize(Users = "Alice,Bob")]public class ValuesController : ApiController{}// Restrict by role:[Authorize(Roles = "Administrators")]public class ValuesController : ApiController{}

Note: The AuthorizeAttribute filter in the Web API is in the namespace System. web. in Http, there is a similar filter in the MVC Controller, which is defined in System. web. in Mvc, they are not compatible.

 

Custom Authorization Filters

A custom authorization filter derives from the following types:

  • AuthorizeAttribute. Extend this class to complete the authorization logic based on the current user and role.
  • AuthorizationFilterAttribute. Extend the authorization logic for this class to complete synchronization. This method must be based on the current user and role.
  • IAuthorizationFilter. Implement this interface to complete asynchronous authorization logic. For example, if your authorization logic uses asynchronous I/O or network calls (If your authorization logic is CPU-Bound, it is the same as a simple derivative from AuthorizationFilterAttribute, because you do not need to write an Asynchronous Method)

The following dimo-shows the class hierarchy forAuthorizeAttributeClass.

The following figure shows the AuthorizeAttribute class level:

Authorize in Controller Action

Sometimes, you may allow a request to continue, but change its behavior according to principal. For example, the information you return depends on the change of the user role. In the Controller method, you can obtain the current principal through the ApiController. user attribute.

public HttpResponseMessage Get(){    if (User.IsInRole("Administrators"))    {        // ...    }}

Ps. Barely translate the content of this article. It should be the study notes.

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.