Browser security prevents a Web page from submitting requests to another domain, which is called the Same-origin Policy, which organizes a malicious website to read sensitive data from another site, but in some special cases you need to allow another site to request your site across domains.
Cross-domain resource sharing (Cors:cross Origin resources sharing) is a global standard that allows servers to relax restrictions on the same domain policy, using CORS, where servers can explicitly allow cross-domain requests and reject other requests. Cors is more secure and flexible than JSONP, and this chapter focuses on how to turn cors on in your ASP. NET 5 application.
What is "same domain"
Two URLs that contain the same protocol, host address, and port number are in the same domain or are referred to as homology.
The following two URLs are the same domain
- Https://www.markyou.cn/a.html
- Https://www.markyou.cn/b.aspx
The URLs in the following are not the same domain
- http://www.markyou.cn
- https://www.markyou.cn
- https://blog.markyou.cn
- https://blog.markyou.cn:8088
Note: IE ignores the port number when judging the same domain
Add a Cors Package
In the project's Project.json file, add the following:
"Dependencies": { "Microsoft.AspNet.Cors": "1.0.0-beta6" },
Configuring Cors in the Application
This section shows how to configure Cors, first, add the Cors service and add the following in Startup.cs:
Public void configureservices (iservicecollection services) { services. Addcors ();}
Next, configure the cross-domain rule, use the Corspolicybuilder class, there are two ways to configure, first, call the Usecors method and use a lambda expression:
Public void Configure (Iapplicationbuilder app) { = = Builder. Withorigins ("http://example.com"));}
All of the configuration details will be parsed in detail later, and now only need to know in this example that this rule only allows cross-domain requests from http://example.com.
Note that this corspolicybuilder has a streaming API, so you can call the method in such a chained way:
App. Usecors (builder = builder). Withorigins ("http://example.com") . Allowanyheader () );
The second way you define one or more cors policies first, and then use the name selection policy at run time:
Public voidconfigureservices (iservicecollection services) {services. Addcors (); Services. Configurecors (Options={options. Addpolicy ("Allowspecificorigin", builder= Builder. Withorigins ("http://example.com")); });} Public voidConfigure (Iapplicationbuilder app) {app. Usecors ("Allowspecificorigin");}
This defines a cors rule called Allowspecificorigin, which is passed to the Usecors method at runtime.
Cors Policy Options
This section describes several options when you configure a Coro policy.
Set the allowed domains
Allows one or more specified domains:
Options. Addpolicy ("allowspecificorigins"={ Builder. Withorigins ("http://example.com""http://www.contoso.com " );});
All domains are allowed:
Options. Addpolicy ("allowallorigins", + = { Builder. Allowanyorigin (); });
Before allowing all domains to be considered carefully, this will mean that any Web site will be able to invoke your app via AJAX requests.
To set the allowed HTTP methods
Specifies which HTTP methods allow access to resources:
Options. Addpolicy ("allowspecificmethods", + = { Builder. Withorigins ("http://example.com") . Withmethods ("GET""POST"" HEAD " ); });
All HTTP methods are allowed:
Options. Addpolicy ("allowallmethods", + = { Builder. Withorigins ("http://example.com") . Allowanymethod (); });
This affects the antecedent request and the Access-control-allow-methods request header.
Set the allowed request headers
A cors advance request may contain the Access-request-headers header, which lists the HTTP request headers for the application.
Specify the allowed request header to Whitelist:
options. Addpolicy ( " allowheaders " => {BU Ilder. Withorigins ( " http://example.com " " accept " , " content-type " Span style= "COLOR: #800000" > ", " origin ", " X-custom-header " ); });
All request headers are allowed:
Options. Addpolicy ("allowallheaders", + = { Builder. Withorigins ("http://example.com") . Allowanyheader (); });
All browsers are not exactly consistent with what access-control-request-headers is set up, so join any other headers you set aside "*" unexpectedly, you should include at least "accept", "Content-type", " Origin ", then add the request header you want to support.
Set the exposed response header
By default, the browser does not expose all the response headers, and the default available response headers are as follows:
- Cache-control
- Content-language
- Content-type
- Expires
- Last-modified
- Pragma
Cors can be called by simple methods to make other response headers available:
Options. Addpolicy ("exposeresponseheaders", + = { Builder. Withorigins ("http://example.com") . Withexposedheaders ("x-custom-header"); });
Credentials in a cross-domain request
Credentials require special handling in cors, and by default the browser does not send any credentials in cross-domain requests. The credentials contain cookies other than the HTTP authentication scheme. In order to send credentials in a cross-domain request, the client needs to set XMLHttpRequest's Withcredentials property to True:
var New XMLHttpRequest (); Xhr.open ('get'http://www.example.com/api/ Test'true;
In jquery:
$.ajax ({ ' get ', ' http://www.example.com/home ', xhrfields: { True }
Similarly, the server side must also allow credentials:
Options. Addpolicy ("allowcredentials", + = { Builder. Withorigins ("http://example.com") . Allowcredentials (); });
Now, the HTTP response will contain a access-control-allow-credentials header that tells the browser that the server allows credentials to be included in cross-domain requests.
If the browser sends credentials, but the request does not contain a valid Access-control-allow-credentials header, the browser will not expose the response in the application and the AJAX request will be faulted.
When allowing vouchers to be quite careful, it means that a site of its domain will be able to send the credentials of a successful user to your application without the user's knowledge. Cors also stipulates that setting the domain to "*" is not valid if the credentials are allowed to exist.
Set the expiration time for an advance request
The Access-control-max-age header specifies the time at which the response of the antecedent request can be cached. Set this header:
Options. Addpolicy ("setpreflightexpiration", + = { Builder. Withorigins ("http://example.com") . Setpreflightmaxage (Timespan.fromseconds (2520) );
How does cors work?
This section describes what happens in the HTTP message level Cors request. This is important to understand how cors works, so that you can properly configure your cors strategy and analyze why your application doesn't work as expected.
The Cors rule proposes several new HTTP headers to open cross-domain requests. If your browser supports cors, it will automatically set the request header for cross-domain settings, and you do not need to do any special processing in JavaScript.
The following is an example of a cross-domain request where the origin header sets which domain makes the requested information:
GET http://myservice.azurewebsites.net/api/test http/1.1referer:http://myclient.azurewebsites.net/ */*Accept-language:en-usorigin:http://myclient.azurewebsites.netAccept- Encoding:gzip, Deflateuser-agent:mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; trident/6.0) Host:myservice.azurewebsites.net
If the server allows this request, it will set a access-control-allow-origin header that matches the origin value of the request or is a * wildcard, which means that all domains are allowed:
http/1.1 okcache-control:no-cachepragma:no-cachecontent-type:text/plain; Charset=utf-8Access-control-allow-origin:http://06:27:30 gmtcontent-length: Test Message
If the response does not include the Access-control-allow-origin header, the AJAX request will fail, but if the browser does not allow the request, the browser will not use the response correctly, even if the server translates a successful response.
Advance request
In some cors requests, the browser sends an additional request before sending a request for a real request for a resource called "Preflight request" (the antecedent in this article), and the browser can ignore the antecedent request if the following conditions are met:
- The request method is, or post
- Applications except Accept-language, Content-language, Content-type and Last-event-id do not set any other request headers
- The Content-type header is one of the following:
- application/x-www-form-urlencoded
- Multipart/form-data
- Text/plain
The rules set in the header are applied by the application calling XMLHttpRequest's Setrequesthander method, and the rules do not apply to the browser's own head, such as User-agent, Hosts, Content-length.
The following is an example of an advance request:
OPTIONS http://myservice.azurewebsites.net/api/test http/1.1*/*origin:http:// Myclient.azurewebsites.netAccess-control-request-method:putaccess-control-request-headers:accept , x-my-custom-headeraccept-encoding:gzip, Deflateuser-agent:mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; trident/6.0) Host:myservice.azurewebsites.netContent-length:0
An advance request uses the HTTP options method, which contains two special headers:
- Access-control-request-method: The HTTP method that will be used in the real request
- Access-control-request-headers:: Set the list of headers in the real request (also does not contain the browser's own request header)
The following is an example and assumes that the service side allows the request:
http/1.1 okcache-control:no-cachepragma:no-cachecontent-length:0Access- control-allow-origin:http://myclient.azurewebsites.netAccess-control-allow-headers:x-my-custom- Headeraccess-control-allow-06:33:22 GMT
The response contains a access-control-allow-methods header that lists the allowed methods, as well as an additional access-control-allow-headers header that lists the allowed request headers, if the antecedent request succeeds, The browser then sends the actual request as described above.
Original address: http://docs.asp.net/en/latest/security/cors.html
Cross-domain request functionality in an ASP. NET 5 Application