1. What is cross-domain
Cross-domain access refers to cross-domain access. The following cases are cross-domain access:
Cross-domain phenomenon | The instance |
---|---|
Different domain names | www.baidu.com withwww.taobao |
The level-1 domain names are the same, but the ports are different | www.baidu.com:8080 与 www.baidu.com:9090 |
The secondary domain name is different | news.baidu.com 与baike.baidu.com |
Note: If the domain name and port number are the same but the requested path is different, the domain name is not cross-domain. For example, www.baidu.com/item www.baidu.com/guonei
2. Why cross-domain issues
Tpis: Cross-domain does not necessarily have cross-domain problems.
Because cross-domain issues are a security limitation that browsers place on Ajax requests:
Ajax requests from a page can only be in the path of the same domain name as the current page, which can effectively prevent cross-site attacks.
If there is no such restriction, js scripts in any website can carry out malicious attacks on any other websites, because cookies are important data saved on the browser side. In this way, you can use cookies to access cross-domain websites opened by the same browser, which has serious security risks.
Therefore: Cross-domain issues are a limitation against Ajax.
However, this is inconvenient for our development, and in the actual build environment, there will certainly be many servers interacting with each other, with different addresses and ports
3. Solutions to cross-domain problems
At present, there are three mainstream solutions to cross-domain problems:
- jsonp
Early cross-domain mainstream solutions, the principle throughscript
Tags are implemented across domains - Limitations: *
- Server support is required
- Can only be initiated
GET
Request, big limitation
-
Nginx reverse proxy
-
Idea: * Use nginx direction proxy function, the original cross-domain request proxy for non-cross-domain, support a variety of request methods
-
Disadvantages: * Requires additional configuration on the nginx server and a large number of domain names to maintain, which can be confusing
-
CORS is currently the mainstream cross-domain solution, which is safe and reliable and widely used at present. Advantage:
- Control is performed on the server side to determine whether cross-domain is allowed, and rules can be customized
- Support various request methods (seven request methods are supported)
- Disadvantages: *
- Additional requests are generated
4. Solution details
4.1 CORS Cross-domain Solution
4.4.1 CORS profile
CORS is a W3C standard, which stands for “Cross-origin Resource Sharing”.
It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.
CORS requires both browser and server support. Currently, all browsers support this function, and Internet Explorer cannot be lower than Internet Explorer 10.
-
Browser side: Currently, all browsers support this feature (not under IE10). The entire CORS communication process is completed automatically by the browser without user participation.
-
Server side: CORS communication is no different from AJAX, so you don’t need to change the old business logic. However, the browser will carry some header information in the request, which we need to determine whether to run it across domains, and then add some information to the response header. This is usually done through a filter
4.1.2 principle
Current browsers categorize our Ajax requests into simple requests and special requests based on how they are handled
A simple request must meet the following two conditions: 1) The request mode must be one of the following:
HEAD
GET
POST
2) The HTTP request header cannot exceed the following fields:
Accept
Accept-Language
Content-Language
Last-Event-ID
Conten-Type
: can only beapplication/x-www-form-urlencoded
,multipart/form-data
,text/plain
Any one of the three
When the browser realizes that the ajax request being sent is a simple one, it carries a field in the request header: Origin.
Origin indicates which domain (protocol + domain + port) the current request belongs to. Based on this value, the service decides whether to allow it to cross domains.
If the server allows cross-domain, you need to return the following information in the response header:
Access-Control-Allow-Origin: http://manage.leyou.com
Access-Control-Allow-Credentials: true
Content-Type: text/html; charset=utf-8Copy the code
- Access-control-allow-origin: Indicates an acceptable domain name. It can be a specific domain name or *, which stands for any domain name
- Access-control-allow-credentials: Specifies whether cookies are allowed. By default, CORS does not carry cookies unless this value is true
Note:
If a cross-domain request wants to operate on cookies, three conditions need to be met:
- Need to be carried in the response header of the service
Access-Control-Allow-Credentials
And is true. - Browser ajax initiation needs to be specified
withCredentials
To true - In the response header
Access-Control-Allow-Origin
Must not be, *Must be the specified domain name **
Special request
If a simple request does not meet the requirements, the browser considers it as a special request. For example, the request mode is PUT.
Preview the request
Special requests are preceded by an HTTP query request, called a “preflight” request.
The browser asks the server if the domain name of the current web page is on the server’s license list, and what HTTP verb and header fields can be used. The browser issues a formal XMLHttpRequest request only if it receives a positive response; otherwise, an error is reported.
A sample “precheck” request:
OPTIONS /cors HTTP/1.1 Origin: http://baike.baidu.com access-Control-request-method: PUT Access-Control-Request-Headers: X-Custom-Header Host: api.leyou.com Accept-Language: en-US Connection: Keep alive - the user-agent: Mozilla / 5.0...Copy the code
In addition to Origin, there are two more headers than simple requests:
Access-Control-Request-Method
: Request method to be used next, such as PUTAccess-Control-Request-Headers
: Additional header information to be used
Precheck the response to the request
The service receives a precheck request and issues a response if the permission is cross-domain:
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://baike.baidu.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Max-Age: 1728000
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plainCopy the code
In addition to the access-Control-allow-origin and access-Control-allow-credentials, there are three additional headers:
Access-Control-Allow-Methods
: Allows accessAccess-Control-Allow-Headers
: Allowed headAccess-Control-Max-Age
: The duration of this license, in seconds, before the expiration of ajax requests do not need to be prechecked again
If the browser gets the above response, it is considered cross-domain, and the subsequent processing is the same as a simple request.
4.1.3 Code implementation
When we implement it in code, it’s actually very simple, but we just need to understand that we don’t need to worry about the browser side, the browser side will handle it automatically. We only care about processing on the server side, we can be very specific on the server side. Note:
- All controller layers need to be processed
- All requests need to be processed across domains
In this case, typical AOP thinking, we can use interceptors to achieve this function; In fact, we have implemented the cross-domain filter of CORS in springMVC framework, we just need to call processing directly; We use Javacondif to write the configuration, which requires support from Spring3 or later. You can also use the traditional XML form, which is not described here. The specific code is as follows:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { //1. CorsConfiguration config = new CorsConfiguration(); Config. AddAllowedOrigin ("http://manage.i-code.online"); / / config. 2) whether to send the Cookie information setAllowCredentials (true); //3) Config. addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); // 4) Config. addAllowedHeader("*"); //5) Valid duration config.setmaxage (3600L); / / 2. Add the mapping path, we intercept all request UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource (); configSource.registerCorsConfiguration("/**", config); Return new CorsFilter(configSource); //3. }}Copy the code
This article was published by AnonyStar. It may be reproduced but the original source must be claimed. Admire “the Art of elegant coding” firmly believe that practice makes perfect, and strive to change your life