What is cross-domain access

When it comes to cross-domain access, we must first explain a term: same-origin policy. The same origin policy means that a browser sends a request to the server using the same protocol, Host(IP address), and port for security purposes. Otherwise, the access is prohibited. The access is also called cross-domain access. Although cross-domain access is prohibited, the security of application can be improved to a certain extent, but it also brings some troubles for development. For example, we developed an easy-to-use system with the separation of the front and back ends. The page and JS are deployed in the Nginx service of a host, and the back-end interface is deployed in a Tomcat application container. When the front end sends a request to the back end, it must not comply with the same origin policy, so it cannot be accessed. So how do we solve this problem? This is what this article needs to explain to you.

What are the solutions for cross-domain access?

2.1. The first type of solution: front-end solution

Browsers prohibit access that does not comply with the same origin policy, but there are exceptions. For example, the following resources reference labels that are not subject to the same origin policy:

  • HTML script tag
  • HTML link tag
  • The IMG tag of HTML
  • HTML iframe tags: For projects developed using JSPS and Freemarker, this is the most common way to achieve cross-domain access,

In addition to implementing cross-domain access based on the features of HTML itself, we can also implement cross-domain access using JSONP, postMessage of Windows. These are the ways in which the front end implements cross-domain access.

2.2. The second type of solution: use a proxy

Cross-domain access support is actually easier to implement on the server side, most commonly through proxies, such as:

  • Nginx or HaProxy proxies cross domains
  • Nodejs middleware proxies cross domains

In fact, the logic of realizing proxy cross-domain is very simple: it is to build an intermediate layer at the front end of different resource services: JS resource, HTML resource, CSS resource and interface data resource service, and all browser and client access are forwarded by proxy. Therefore, both browsers and clients access resources with the same IP address and port, which complies with the same origin policy to implement cross-domain access.

2.3 The third scheme: CORS

Cross-domain resource sharing (CORS) : Implements cross-domain resource sharing by modifying Http protocol headers. Simply put, the HTTP response Header tells the browser which situations can be accessed across domains that do not comply with the same origin policy. The browser makes specific judgments by parsing the HEADERS in the HTTP protocol. The specific headers are as follows:

CROS cross-domain common headers

  • Access-control-allow-origin: Specifies the IP addresses or domain names that can be accessed across domains
  • Access-control-max-age: indicates the number of seconds in which the cross-domain Access permission of the request does not need to be checked repeatedly
  • Access-control-allow-methods: HTTP Methods that Allow cross-domain requests, such as GET,POST,PUT, and DELETE
  • Access-control-allow-headers: Specifies which Headers are allowed to be carried in an Access request. For example:Accept,Accept-Language,Content-Language,Content-Type

Four ways to realize CORS under SpringBoot

We introduce four methods to implement CORS, two are global configuration, two are local interface effective configuration. Typically, SpringBoot projects implement CORS in one of these ways.

3.1. Use CorsFilter for global cross-domain configuration

@Configuration public class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); Config. AddAllowedOrigin ("*"); config. AddAllowedOrigin ("*"); / / is it allowed to send the Cookie information config. SetAllowCredentials (true); Config. addAllowedMethod("GET","POST", "PUT", "DELETE"); Config. addAllowedHeader("*"); Config. AddExposedHeader ("*"); // Add mapping path, "/ * *" in the path of all global cross-domain access Settings UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource (); configSource.registerCorsConfiguration("/**", config); return new CorsFilter(configSource); }}Copy the code


3.2. Rewrite the addCorsMappings method of WebMvcConfigurer (global cross-domain configuration)

@Configuration public class GlobalCorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() {@override public void addCorsMappings(CorsRegistry registry) {registry. AddMapping ("/**") // Adding a mapping path, AllowedOrigins ("*") // Which IP addresses, ports, and domain names are allowed to access. AllowCredentials (true) // Whether cookies are allowed to be sent .allowedMethods("GET","POST", "PUT", "DELETE") AllowedHeaders ("*") // What headers are allowed to be carried in HTTP requests. ExposedHeaders ("*"); Which headers are exposed (because cross-domain access defaults to not getting all headers)}}; }}Copy the code


3.3. Using CrossOrigin annotations (local cross-domain configuration)

  • Add CrossOrigin annotations to Controller layer methods that define RequestMapping endpoints that support cross-domain access
  • Add CrossOrigin annotations to the class definition at the Controller layer and the RequestMapping endpoints corresponding to all the methods of the class will support cross-domain access
    @RequestMapping("/cors")
    @ResponseBody
    @CrossOrigin(origins = "http://localhost:8080", maxAge = 3600) 
    public String cors( ){
        return "cors";
    }Copy the code

3.4 Setting response Headers using HttpServletResponse (local cross-domain configuration)

This approach is somewhat cumbersome and is not recommended for SpringBoot projects.

@RequestMapping("/cors") @ResponseBody public String cors(HttpServletResponse response){ // Use HttpServletResponse to define the HTTP request header, Response. addHeader(" access-Control-allow-origin ", "http://localhost:8080"); return "cors"; }Copy the code

Implementation and testing

Define a random HTML outside of the SpringBoot project and write code that triggers the following Ajax code. (I will not write the trigger process, define a button and a listener function). Here is the core code for cross-domain AJAX request validation:

$. Ajax ({url: 'http://localhost:8090/cors', type: "POST", xhrFields: {} withCredentials: true / / allow to send the Cookie information, success: Function (data) {alert(" alert(")}, error: function (data) {alert(")}})Copy the code

  • The successful configuration of the cross-domain request indicates that our cross-domain configuration is effective and the Ajax request can access the server interface correctly.
  • If the cross-domain request configuration fails, the cross-domain configuration does not take effect. Please refer to section 3 to check whether the configurations are correct.

We look forward to your attention

  • The blogger has recently written a new book: “SpringBoot Series – Chapter 16, Verse 97.”
  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.