1. Introduction to CORS
The homologous strategy (same origin policy) is the cornerstone of browser security. Under the same-Origin policy restrictions, AJAX requests cannot be sent between sites that are not homologous.
In order to solve this problem, a cross-source resource sharing, CORS (Cross-origin Resource sharing) is proposed.
Cors achieves two points: without destroying the regular server implements the Cors interface, it can cross-source communication
Based on these two points, CORS divides the requests into two categories: simple and non-simple requests. 1.1 Simple Requests
You can start by looking at the pre-CORS scenario where you can trigger a GET request or send a POST request through a form through a script or an image tag across sources, but neither of these request HTTP header messages can contain any custom fields.
Simple request pairs should rule, so the definition of a simple request is:
The request method is head, GET, or POST and the HTTP header information does not exceed the following fields: Accept, Accept-language, Content-language, Last-event-id, Content-type (limited to application/x-www-form-urlencoded, Multipart/form-data, Text/plain).
For example, there is a simple request:
Get/test http/1.1
Accept: */*
accept-encoding:gzip, deflate, SDCH, BR
origin:http://www.examples.com
Host:www.examples.com
For such a simple request, CORS's policy is to request, * * Add an Origin field in the header information * *, after the server receives the request, according to the field to determine whether to allow the request. If allowed, adds the Access-control-allow-origin field to the HTTP header information and returns the correct result if not allowed, the Access-control-allow-origin field is not added to the header information.
The browser first gets the results back to the user, depending on whether or not the Access-control-allow-origin field is available to intercept the return result.
For some of the pre-cors services, cors affects them in two ways: script or image-triggered GET requests do not contain Origin headers, so they are not restricted by cors and are still available. In the case of an AJAX request, the HTTP header contains the Origin field, and since the server does not have any configuration, the returned result will not contain access-control-allow-origin, so the returned result is blocked by the browser, and the interface is still not available for Ajax Cross-origin access.
As you can see, the advent of CORS does not have any effect on the "old" service.
Also, in addition to the mentioned Access-control-allow-origin, there are several fields that describe the CORS return result: access-control-allow-credentials: Optional, whether the user can send or process cookies. Access-control-expose-headers: Optional, allows the user to get the field. There are several fields that can be obtained whether set or not, including: Cache-control, Content-language, Content-type, Expires, Last-modified, Pragma. 1.2 Non-trivial requests
A request other than a simple request is a non-simple request.
For cross-origin requests for non-simple requests, * * The browser adds an OPTION request, called a preflight request, before the real request is issued. The preflight request adds the information for the real request, including the request method, the Custom header field, and the source information to the HTTP header information field, asking the server if it allows such an operation.
For example, DELETE request:
Options/test http/1.1
origin:http://www.examples.com
access-control-request-method:delete
Access-control-request-headers:x-custom-header
Host:www.examples.com
CORS-related fields are: Access-control-request-method: The HTTP method used by the real request. Access-control-request-headers: A custom header field contained in a real request.
When the server receives the request, it needs to verify the Origin, Access-control-request-method, and Access-control-request-headers separately, and after the validation is passed, the Http header information is added
Access-control-allow-origin:http://www.examples.com
Access-control-allow-methods:get, POST, PUT, DELETE
Access-control-allow-headers:x-custom-header
access-control-allow-credentials:true
access-control-max-age:1728000
Their meanings are: Access-control-allow-methods: The method allowed by the real request Access-control-allow-headers: The field that the server is allowed to use Access-control-allow-credentials: Whether to allow users to send, process cookies Access-control-max-age: The validity period of the preflight request, in seconds. The pre-check request is not repeated during the validity period
When the preflight request passes, the browser sends a real request to the server. This enables cross-origin requests.
Now that you've learned about Cors, let's build a simple spring MVC service and learn more about how spring MVC configures CORS. 2. Spring MVC Environment Setup
Open http://start.spring.io/, add Web Dependency, and select Generate Project, download the zip file and get a spring boot demo.
Unzip the zip file, double-click Pom.xml to open it or use idea, Eclipse to import the project according to Maven.
Depending on the Group, Artifact, Dependencies, the project directory structure may be slightly different, my project structure is as follows:
├──SRC
│ ├──main/java
│ | └──net/xiayule/spring/cors
│ | └──springbootcorstestapplication.java
| └──resources
| ├──static
| ├──templates
| └──application.properties
|
└──pom.xml
The only thing we need to care about is Springbootcorstestapplication.java. Add the following code to Springbootcorstestapplication.java:
@RestController
@SpringBootApplication Public
class Springbootcorstestapplication {
@RequestMapping ( Value = "/test") Public
String Greetings () {
return "{\" project\ ": \" Just a Test\ "}";
}
public static void Main (string[] args) {
springapplication.run (springbootcorstestapplication.class, args);
}
}
The meaning of the @RequestMapping (value = "/test") is that the method accepts a request from/test and provides support for methods such as GET, POST, DELETE, and so on for HTTP.
To run the project, start the app mvn spring-boot:run the project root and open the browser to access http://localhost:8080 to see the effect:
The backend service is set up and then the front end is implemented. For simplicity, create a test.html file directly and add the following:
<! DOCTYPE html>
Opening the file with a browser triggers a request to http://localhost:8080. You can trigger different types of requests by modifying the method of the above code.
Since it is opened directly using the browser, * * The source of the Web page is null**, and when the request is made to the source http://localhost:8080, it becomes a cross-origin request, so if the backend is not CORS-configured, the HTTP header information returned will not contain Access-control-allow-origin, so the browser will report the following error:
3. Configure CORS
An app may have multiple cors configurations, and each cors configuration can be set up for an interface or a series of interfaces or for all interfaces to take effect.
For example, we need to: let the/test interface support cross-source access, while other interfaces such as/TEST/1 or/API do not support cross-origin access to allow/test/* this type of interface to support cross-origin access, while other interfaces such as/API do not support cross-origin access all interfaces support cross-source access
In the first case, if you want to configure CORS on an interface, you can add crossorigin annotations on the method:
@CrossOrigin (Origins = {"http://localhost:9000", "null"})
@RequestMapping (value = "/test", method = requestmethod.get) Public
String Greetings () {
return "{\" project\ ": \" Just a Test\ "}";
}
In the second case, if you want to add a CORS configuration to a series of interfaces, you can add annotations on the class that declare all interfaces valid:
Crossorigin (Origins = {"http://localhost:9000", "null"})
@RestController
@SpringBootApplication
public class Springbootcorstestapplication {
//XXX
}
In the third case, to add a global configuration, you need to add a configuration class:
@Configuration public
class Webconfig extends Webmvcconfigureradapter {
@Override public
Void Addcorsmappings (Corsregistry registry) {
registry.addmapping ("/**")
. Allowedorigins ("http://localhost : 9000 "," null ").
allowedmethods (" POST "," GET "," PUT "," OPTIONS "," DELETE ").
maxAge (3600)
. Allowcredentials (True);
}
}
In addition, you can configure CORS rules by adding a Filter, and manually specify which interfaces are valid.