1. Introduction

Most web projects today use the Spring series of frameworks, and as technology shifts away from traditional JSP/Servlet projects, new projects often use the principle of front – and back-end separation. This has the advantage of improving development efficiency by separating the boundaries between front-end and back-end projects, as well as facilitating project testing and maintenance.

The most common and core problem in the projects with separated front and back ends, no matter Spring Boot or Spring Cloud projects, is cross-domain problem. Because front-end and back-end projects are on different server ports, in other words, the project ports are not shared and data cannot be directly transmitted. This is where cross-domain issues for the project must be set.

2. What is cross-domain?

Cross-domain means that the browser cannot execute scripts from other sites. It is caused by the same origin policy of the browser, a security restriction that the browser imposes on javascript.

[1]. What is the same-origin policy?

Netscape introduced the same origin policy into the browser in 1995. It is the core and most basic security function of the browser. Without the same origin policy, the browser is vulnerable to XSS and CSFR attacks. Same-origin means that the protocol, domain name, and port are the same. Even if two different domain names point to the same IP address, they are not same-origin.

The same origin policy restricts the following behaviors:

  • Cookie, LocalStorage, and IndexDB cannot be read
  • DOM and JS objects are not available
  • AJAX requests cannot be sent

[2]. Common cross-domain scenarios

URL instructions Whether to allow communication
www.domain.com/a.js www.domain.com/b.js www.domain.com/lab/c.js Same domain name, different file or path allow
www.domain.com:8000/a.js www.domain.com/b.js Same domain name, different port Don’t allow
www.domain.com/a.js www.domain.com/b.js Same domain name, different protocol Don’t allow
www.domain.com/a.js http://192.168.4.12/b.js The domain name and domain name correspond to the same IP address Don’t allow
www.domain.com/a.js x.domain.com/b.js domain.com/c.js The primary domain is the same, but the subdomain is different Don’t allow
www.domain1.com/a.js www.domain2.com/b.js Different domain name Don’t allow

3. Cross-domain mode

The cross-domain mode can be divided into front-end cross-domain configuration and back-end cross-domain configuration. Generally, only one configuration is required. That is, the front-end cross-domain configuration does not need to be configured on the back-end.

[1]. Front end cross domain

The front cross domain can be reference for class an article: www.imooc.com/article/291…

This blog focuses on configuring backend projects across domains.

[2]. Back-end cross-domain

Back-end cross-domain is generally divided into two types: the first is to add @crossorigin annotations; The second is to configure the global cross-domain of the project.

Add the @crossorigin annotation

When using Spring Boot 1.x, you can solve the cross-domain problem by adding @crossorigin directly to the Controller layer. However, after Spring Boot 2.x, @crossorigin annotations without configuration information are no longer supported. When @Crossorigin is still used:

@CrossOrigin
@RestController
public class EntryController {
    @Autowired
    privateUserService userService; . }Copy the code

The front-end console may report an error as follows:

Then you configure @crossorigin with the following comment:

@CrossOrigin(origins = "*",maxAge = 3600)
// @restController is the sum of @Controller+ @responseBody
@RestController
public class EntryController {
    @Autowired
    privateUserService userService; . }Copy the code

Be sure to restart the project after the configuration, otherwise it will not take effect, and then generally no error will be reported.

If you still get an error after the above configuration, don’t worry, you should check to see if you have filters and interceptors configured on the back end. If so, At this point, @crossorigin (origins = “*”,maxAge = 3600) cannot be used directly. In this case, configure global cross-domain rules on the back end, as follows.

Configure global cross-domain rules

Create a new config directory under your com.xxx. XXX, and create a new MyCorsConfig class (name can be arbitrary, preferably not the same as the Java library). The code Settings are 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;
// Add configuration annotations
@Configuration
public class MyCorsConfig {
        // Add @bean to Spring's IOC container
        @Bean
        public CorsFilter corsFilter(a) {
           // Create a cross-domain configuration
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            // Allow all request sources (urls)
            corsConfiguration.addAllowedOrigin("*");
            // Allow all request headers
            corsConfiguration.addAllowedHeader("*");
            // Allow method names contained in all request urls
            corsConfiguration.addAllowedMethod("*");
             // Allow all request urls to include the user's credentials
            corsConfiguration.setAllowCredentials(true);
            // Create a URL-based configuration source
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            // Register cross-domain rules (similar to add method in List)
            source.registerCorsConfiguration("/ * *", corsConfiguration);
            return newCorsFilter(source); }}Copy the code

Note: You do not need to configure @crossorigin annotations after configuring global cross-domain rules.

After the configuration is complete, restart the project and no error will be reported.

4. To summarize

Cross-domain problems in the development of web applications will often encounter, and in the solution to cross-domain problems using the front-end solution can choose too many options and can not find the right solution, then it is better to communicate with the back-end development brother, directly back-end configuration cross-domain on the line, simple and save trouble (dog head protection).

If you have any other solutions or questions about this problem, feel free to leave a comment! (This article is updated with the SegmentFault Community article.)