Support for CORS by ASP. NET Web APIs: Implementation of CORS authorization Verification

Source: Internet
Author: User

Through the story behind the EnableCorsAttribute feature, we know that CorsPolicy provided by CorsPolicyProvider indicates the resource authorization policy used by the target Action, ASP. NET Web API needs to use it to implement authorization verification for specific cross-origin resource requests and generate the corresponding CORS response header. In the Application Programming Interface of ASP. NET Web API, the result of resource authorization test is represented by the Type CorsResult. 1. CorsResultCorsResult is defined in the namespace "System. web. cors indicates the result of the resource provider's authorization test for specific cross-origin resource requests. The CORS headers written to the response are generated using this object. As shown in the following code snippet, CorsResult still has attributes corresponding to six CORS Response Headers. The Dictionary of its ToResponseHeaders method indicates the corresponding CORS headers generated by these six attributes, the Key and Value of the dictionary object indicate the header name and Value respectively. 1: public class CorsResult 2: {3: public string AllowedOrigin {get; set;} 4: public IList <string> AllowedExposedHeaders {get;} 5: public IList <string> AllowedHeaders {get;} 6: public IList <string> AllowedMethods {get;} 7: public long? PreflightMaxAge {get; set;} 8: public bool SupportsCredentials {get; set;} 9: 10: public IList <string> ErrorMessages {get;} 11: public bool IsValid {get;} 12: 13: public virtual IDictionary <string, string> ToResponseHeaders (); 14 :} corsResult has a Boolean attribute IsValid, indicating whether the request passes the resource authorization check. If this attribute returns False (the resource authorization test is not passed), another related attribute ErrorMessages will provide the cause of the test failure. IsValid is a read-only attribute. Its value depends on whether the string list indicated by the ErrorMessages attribute is empty. Ii. CorsRequestContext's support for CORS is not limited to being used only in ASP.. NET Web API, used to verify the authorization of cross-origin resource requests based on the provided resource authorization policies. The engine is defined in the assembly System. web. cors. dll, defined in another assembly for these types, except that CorsPolicy is defined in the assembly System. web. cors. dll, and Other types are defined in the assembly System. web. http. cors. the related types in dll can be considered as extensions to this core CORS engine. For the type introduced in this section, its namespace actually reflects its assembly. For ASP. NET Web APIs, the purpose of CORS resource authorization verification is to indicate the HttpRequestMessage object requested. This object is naturally not available in the core CORS engine of ASP. NET. For the latter, the authorization check is for a System. Web. Cors. CorsRequestContext object, which represents the context of the current request. As shown in the following code snippet, we can use the CorsRequestContext object to obtain the corresponding HTTP request address (RequestUri), Host name (Host), and HTTP method (HttpMethod ). 1: public class CorsRequestContext 2: {3: public Uri RequestUri {get; set;} 4: public string Host {get; set;} 5: public string HttpMethod {get; set;} 6: 7: public string Origin {get; set;} 8: public bool IsPreflight {get;} 9: public string AccessControlRequestMethod {get; set;} 10: public ISet <string> AccessControlRequestHeaders {get;} 11: 12: public IDictionary <string, object> Prop Erties {get;} 13 :} the Origin attribute of CorsRequestContext returns the source site represented by the request's "Origin" header. We can use its IsPreflight attribute to determine whether an HTTP request is a pre-check request. Here, the pre-check request criteria are exactly the same as the ones used in the previous example: the HTTP-OPTIONS Method is used to discard headers with both "Origin" and "Access-Control-Request-Method. For the CorsRequestContext of the pre-check Request, we can obtain the values of the Request Header "Access-Control-Request-Method" and "Access-Control-Request-Headers" through its attributes AccessControlRequestMethod and AccessControlRequestHeaders. Using the read-only attribute Properties of another dictionary type, we can attach any object as the attribute to this CorsRequestContext object. Iii. CorsEngine: ASP. the core CORS engine of NET is defined in the assembly System. web. cors. in dll, it mainly experiences the object named CorsEngine, its main mission is: according to the provided resource Authorization Policy (represented by CorsPolicy type) perform authorization tests for specific cross-origin resource requests (expressed by CorsRequestContext type) and obtain the corresponding authorization results (indicated by CorsResult ). All CorsEngine types implement the System. Web. Cors. ICorsEngine interface, as shown in the following code snippet. The cross-origin resource request authorization check is implemented in its unique EvaluatePolicy method. 1: public interface ICorsEngine 2: {3: CorsResult EvaluatePolicy (CorsRequestContext requestContext, CorsPolicy policy); 4:} in the assembly System. web. cors. dll defines the unique implementation of the ICorsEngine interface, which has the following defined types: System. web. cors. corsEngine. As shown in the following code snippet, The CorsEngine type defines three auxiliary Virtual Methods (TryValidateOrigin, TryValidateMethod, and TryValidateHeaders) authorization tests are performed on the Origin Site of the request and the HTTP method and custom header used by the request. The latter two methods are specially designed for precheck requests. 1: public class CorsEngine: ICorsEngine 2: {3: public virtual CorsResult EvaluatePolicy (CorsRequestContext requestContext, role policy); 4: 5: public virtual bool TryValidateOrigin (CorsRequestContext requestContext, role policy, corsResult result); 6: public virtual bool TryValidateMethod (CorsRequestContext requestContext, CorsPolicy policy, CorsResult result); 7: public virtual bool TryValidateHeaders (CorsRequestContext requestContext, CorsPolicy policy, CorsResult result); 8:} Same as CorsPolicyProviderFactory, ASP. the CorsEngine used by the NET Web API needs to be registered to the current HttpConfiguration. The registered CorsEngine is also added to the attribute Dictionary of HttpConfiguration. The registration of CorsEngine can be completed by calling the extension method SetCorsEngine shown in HttpConfiguration as follows. Another extension method, GetCorsEngine, is used to obtain the registered CorsEngine. If CorsEngine is not registered when this method is called, a CorsEngine object is created and automatically registered to HttpConfiguration. 1: public static class CorsHttpConfigurationExtensions 2: {3: // other Member 4: public static void SetCorsEngine (this HttpConfiguration httpConfiguration, ICorsEngine corsEngine); 5: public static ICorsEngine GetCorsEngine (this HttpConfiguration httpConfiguration); 6 :}

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.