Old tired cross-domain problem? Look at what treatment method

Written in front of "IT technical staff of self-cultivation" , I did not expect to receive a lot of good feedback within a few days, thank you for your attention. Will be back from time to time to share some of the technical work lessons learned and insights in the field of management, we welcome the continued focus on the exchange. Asked about a recent issue of cross-domain, including previously found that many interviewers for handling cross-domain and also a smattering of knowledge, so this article has combed summarize the problem, for reference during the interview.

1. What is cross-domain

What is cross-domain understanding, we must first understand a place called "same origin policy" thing, what is the "same origin policy"? This is a browser to access a secure Web site, requests from different sources of a strategy to do the necessary access restrictions. What is called "homologous" mean? We know that an http request address typically includes four parts: 协议://域名:端口/路径the so-called homologous, that is, three in front of that protocol, domain names, ports are the same. Illustration, if we have an address  http://blog.jboost.cn/docker-1.html, to see whether it is homologous to the following address

address Whether homologous Explanation
https://blog.jboost.cn/docker-1.html Different sources Different protocols, a http, https a
http://www.jboost.cn/docker-1.html Different sources Different domain
http://blog.jboost.cn:8080/docker-1.html Different sources Different ports, a port 80 is the default one is 8080
http://blog.jboost.cn/docker-2.html Homologous Although the path is different, but protocol, domain name, port (default 80) are the same

 

Then the browser requests to different sources of what had been done to limit access to it? There are three restrictions

  1. Access to Cookie, LocalStorage, and IndexDB (class NoSQL browser provides a local database)

  2. Access to the DOM

  3. AJAX requests

The cross-domain access is to break this limit, a request for resources from different sources can be carried out smoothly, the most common is the AJAX request, such as the front and rear ends of the splitter architecture, two different domain name service, front-end via AJAX direct access to the server end interface , will cross-domain problems.

2. Why are there cross-domain

He said earlier been mentioned at the "same origin policy" and the browser to access a secure Web site, only to set up cross-domain this barrier. Then the three previously mentioned limitations, are, respectively, how to protect the safety of the site.

  1. Local store Cookie, LocalStorage, IndexDB access restrictions
    login credentials of our system is generally (such as a request for a browser form) by setting SESSIONID in the Cookie or direct return in the form of token (such as for REST request) is returned to the client, such as Tomcat is by setting the property called JSESSIONID in the Cookie to save, and other sites and general REST request token is stored in the front LocalStorage, if access restrictions do not exist, you might get access to these documents, then forge your identity to initiate an illegal request, which is too unsafe.

  2. Access restrictions to the DOM
    if we do not restrict access to the DOM, so other sites, especially some of the phishing site, you can  <iframe> get access to your site DOM form, and then you get to enter sensitive information, such as user name, password ...

  3. AJAX request to limit
    same-origin policy provisions, AJAX request can only be issued to homologous URL, otherwise it will error. As to why the restriction, partly to avoid in an illegal request forgery mentioned, on the other hand I understand that AJAX is too flexible, if not to limit, may interface resource site will be free to use other sites, just like you private goods by others acknowledge me with any take the same. 


In short, the same-origin policy is the most basic kind of security mechanism or agreement provided by the browser.

3. how to achieve cross-domain access

Cross-domain problems we encounter the usual basic AJAX requests appear in the scene, in general, cross-domain problem can be solved through a proxy, CORS, JSONP other ways.

3.1 Proxy

Since the "same origin policy" is the mechanism the browser side, then we can bypass the browser, the most common approach is to use a proxy, such as Nginx, such as the domain name of our front-end project is http://blog.jboost.cn, service end interface domain name is http://api.jboost.cn, we offer the following configurations in Nginx

{Server 
    # port 
    the listen 80; 
    # domain 
    server_name blog.jboost.cn; 
    # http://blog.jboost.cn/api/xxx all requests will be forwarded to http://api.jboost.cn/api/xxx 
    LOCATION ~ ^ / API { 
        proxy_pass http://api.jboost.cn; 
    } 
}

 

AJAX request by the front-end server instead interfaces http://api.jboost.cn/api/xxx can be accessed by http://blog.jboost.cn/api/xxx, different sources so as to avoid the problem of cross-domain . 

3.2 HEARTS

CORS is a Cross-Origin Resource Sharing shorthand, sharing that is cross-domain resources, CORS need the server and the browser supports all current browsers (except IE10 or less) support CORS, therefore, to achieve CORS, mainly the work of the service side of the . Spring Boot example, we can register to support cross-domain filter by a CorsFilter follows.

1  @Configuration
 2 @ConditionalOnClass ({Servlet. Class , CorsFilter. Class })
 3  public  class CORSAutoConfiguration {
 4  
5      @Bean
 6 @ConditionalOnMissingBean (name = "corsFilterRegistrationBean" )
 7  public FilterRegistrationBean corsFilterRegistrationBean () {
 8          UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource ( );
9  
10          CorsConfiguration corsConfiguration = new CorsConfiguration ();
11         corsConfiguration.applyPermitDefaultValues();
12         corsConfiguration.setAllowedMethods(Arrays.asList(CorsConfiguration.ALL));
13         corsConfiguration.addExposedHeader(HttpHeaders.DATE);
14 
15         corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
16 
17         CorsFilter corsFilter = new CorsFilter(corsConfigurationSource);
18         FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
19         filterRegistrationBean.setFilter(corsFilter);
20         filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
21         filterRegistrationBean.addUrlPatterns("/*");
22 
23         return filterRegistrationBean;
24     }
25 }

 

Its essence is to add several properties in the Header response message, there 

  • Access-Control-Allow-Origin necessary, cross-domain representation allows the request source, and may be specific to the domain, may be * indicates Anydomainname

  • Access-Control-Allow-Methods necessary, to allow cross-domain access represents an HTTP method, such as GET, POST, PUT, DELETE and the like, may be *, indicating that all

  • Access-Control-Allow-Headers If the request includes Access-Control-Request-Headers header information is required, it indicates that the server supports all the header field

3.3 JSONP

JSONP browser using HTML some labels (e.g.  <script><img>etc.) having no homology to the src attribute restriction policy implementation characteristics, such as adding a front end

<script type="text/javascript" src="http://api.jboost.cn/hello?name=jboost&callback=jsonpCallback"/>

JS and method definitions  jsonpCallback. The server returns the contents of the interface need to be JS method jsonpCallbackcall format, such as jsonpCallback({"name":"jboost"}), in this way jsonpCallbackyou can get the results of the data server returns the actual method {"name":"jboost"}of.
Limitations JSONP approach is also evident, one only supports GET requests - which you have not seen <script><img>the label is a POST request it, and second, the need to return the data format of the server for processing.

4. Summary

Three inter-implementation support, proxy easiest way, the client, the server is not invasive, but if you need more support request source, or with a third party docking, then the way is not as useful agents . CORS is a relatively standard treatment, and also through the filter without any invasive way to service code. The great limitation JSONP way, only supports GET, and the server needs to do to return data format support. You can select suitable manner for specific situations.

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/spec-dog/p/11277943.html