Authentication and authorization for ASP. net webapi, asp. netwebapi
Definition
Authentication): Determine who the user is.
Authorization): Determine what the user can do and what he cannot do.
Authentication
WebApi assumes that authentication occurs in the Host Program name. For web-hosting, the host is IIS. In this case, use the HTTP Module for verification.
During verification, the host creates a principal object that represents the security context (implementing IPrincipal) and attaches it to the current thread. The subject object contains an Identity object that stores user information. If the verification succeeds, the Identity. IsAuthenticated attribute returns true.
HTTP Message Handler)
You can use an HTTP message processing program to authenticate the host. In this case, the HTTP message processing program checks the request and sets the subject object.
Consider the following to determine whether to use the message processing program for authentication:
- The HTTP Module checks all requests that pass through the asp.net pipeline. The message processing program only checks requests routed to the WebAPI.
- You can set a message handler for each route.
- The HTTP module is only available in IIS. The message processing program is independent of the host and is available in both web-hosting and self-hosting.
- The HTTP module is used for IIS logging, auditing, and other functions.
- The HTTP module runs before the MPs queue. The subject is not set before the message processing program runs. When the response leaves the MPs queue, the subject is restored to the original one.
Generally, the HTTP module is better when no self-bearer is required.
Set subject
When performing custom authentication, you should set the subject object in two places:
- Thread. CurrentPrincipal, which is the standard method for setting Thread subjects in. net.
- HttpContext. Current. User is a property specific to ASP. NET.
private void SetPrincipal(IPrincipal principal){ Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = principal; }}
When web-hosting is used, you must set two locations at the same time to avoid inconsistent security context. For self-hosting, HttpContext. Current is null, so check before setting.
Authorization
Authorization occurs in the pipeline closer to the controller.
- The Authorization filter is run before the action. If the request is not authorized, an error is returned and action is not executed.
- In the action, you can use the ApiController. User attribute to obtain the subject object for further control.
[Authorize] attributes
AuthorizeAttribute is a built-in authorization filter. When the user fails authentication, it returns the HTTP 401 status code. It can be applied at the global, control, and action levels.
Global Application:
public static void Register(HttpConfiguration config){ config.Filters.Add(new AuthorizeAttribute());}
Application at the Controller level:
[Authorize]public class ValuesController : ApiController{ public HttpResponseMessage Get(int id) { ... } public HttpResponseMessage Post() { ... }}
Application at the Action level:
public class ValuesController : ApiController{ public HttpResponseMessage Get() { ... } [Authorize] public HttpResponseMessage Post() { ... }}
When [Authorize] is applied to the Controller, [AllowAnonymous] can be applied to the Action to cancel the authorization requirements for an Action. The above code can be changed to the following format:
[Authorize]public class ValuesController : ApiController{ [AllowAnonymous] public HttpResponseMessage Get() { ... } public HttpResponseMessage Post() { ... }}
Restrict specified users and roles:
// Access [Authorize (Users = "Alice, Bob")] public class ValuesController according to user restrictions: apiController {} // access by role restrictions [Authorize (Roles = "Administrators")] public class ValuesController: ApiController {}
The AuthorizeAttribute used for WebAPI is located in the System. Web. Http namespace. The System. Web. Mvc namespace has an attribute of the same name and cannot be used for WebAPI.
Custom authorization Filter
Custom authorization filters can be derived from the following types:
- AuthorizeAttribute, Authorization based on users and roles.
- AuthorizationFilterAttributeDoes not allow synchronous authorization based on users and roles.
- IAuthorizationFilterTo implement the asynchronous authorization logic. For example, the authorization logic involves asynchronous calls to IO or networks. (The authorization logic of CPU-bound is more suitable for deriving from AuthorizationFilterAttribute, so that asynchronous methods do not have to be written ).
YesAuthorizeAttributeClass hierarchy
Perform verification in Action
You can check the ApiController. User attribute in the Controller and use different logic based on the User and role.
public HttpResponseMessage Get(){ if (User.IsInRole("Administrators")) { // ... }}
Address: http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api