preface

The cross-domain problem of Springboot is a difficult problem for mainstream Web developers. But let’s be clear about the following first

  • Cross-domain only exists on the browser side, not android /ios/Node.js/ Python/Java etc
  • The cross-domain request can be sent, and the server can receive the request and return the result normally, but the result is blocked by the browser.
  • Cross-domain communication is restricted by the same origin policy. Only when the sources are the same, the communication can be normal, that is, the protocol, domain name, and port number are the same.

For security purposes, browsers must comply with the same origin policy when making HTTP requests using XMLHttpRequest objects. Otherwise, the requests are cross-domain HTTP requests and are prohibited by default. In other words, the cornerstone of browser security is the same-origin policy.

The same origin policy restricts how documents or scripts loaded from the same source can interact with resources from another source. This is an important security mechanism for isolating potentially malicious files.

Start with a familiar error message to help you feel at home

Access to XMLHttpRequest at ‘http://192.168.1.1:8080/app/easypoi/importExcelFile’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

What is CORS?

CORS, or Cross-Origin Resource Sharing, is a W3C standard that allows browsers to issue XMLHttpRequest requests to cross-source servers, overcoming the limitation that AJAX can only be used in the same source.

It tells the client about the cross-domain limits by adding a special Header[access-Control-Allow-Origin] to the server, and allows XMLHttpRequest to make a cross-domain request if the browser supports CORS and determines that Origin has passed.

CORS Header

  • Access-Control-Allow-Origin: www.xxx.com
  • Access – Control – Max – Age: 86400
  • Access-control-allow-methods: GET, POST, OPTIONS, PUT, DELETE
  • Access-Control-Allow-Headers: content-type
  • Access-Control-Allow-Credentials: true

Explanation of meaning:

CORS Header properties explain
Access-Control-Allow-Origin allowwww.xxx.com domain (set by yourself, for example only) initiates cross-domain requests
Access-Control-Max-Age Set the prevalidation request to no longer need to be sent at 86400 seconds
Access-Control-Allow-Methods Sets the method to allow cross-domain requests
Access-Control-Allow-Headers Allow cross-domain requests to include content-Type
Access-Control-Allow-Credentials Setting to allow cookies

SpringBoot cross-domain request processing

SpringBoot annotation @crossorigin (also supports SpringMVC)

In a crude way, the Controller layer adds this annotation to classes or methods that need to cross domains

@RestController
@CrossOrigin
@RequestMapping("/situation")
public class SituationController extends PublicUtilController {

    @Autowired
    private SituationService situationService;
    // log Log information
    private static Logger LOGGER = Logger.getLogger(SituationController.class);
    
}
Copy the code

PublicUtilController is a common parent of controllers, which all controllers inherit.

@CrossOrigin
public class PublicUtilController {

    * @param currentPage * @param pageSize * @return */
    public PageInfoUtil proccedPageInfo(String currentPage, String pageSize) {

        / * paging * /
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        try {
            /* * Convert string to integer, risk, string a, conversion is not an integer */
            pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
            pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
        } catch (NumberFormatException e) {
        }
        returnpageInfoUtil; }}Copy the code

Of course, although here refers to the SpringBoot, SpringMVC is the same, but requires Spring4.2 or later.

In addition, if the SpringMVC framework version is not convenient to change, you can also modify the Tomcat web.xml configuration file to handle this

SpringMVC uses @crossorigin to use scenario requirements

  • Jdk1.8 +
  • Spring4.2 +

Method 2. Configuration for handling cross-domain requests

Add a configuration class, Crossoriginconfig.java. Inheriting the WebMvcConfigurerAdapter or implementing the WebMvcConfigurer interface, the configuration is automatically read when the project starts.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/** * AJAX requests across domains */
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    static final String ORIGINS[] = new String[] { "GET"."POST"."PUT"."DELETE" };
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/ * *").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS).maxAge(3600);
    }
Copy the code

Method 3: Adopt the method of filter

In the same way, add a CORSFilter class and implement the Filter interface. When the interface is called, it will Filter cross-domain interception.

 @Component
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        // Set to allow cookies
        res.addHeader("Access-Control-Allow-Credentials"."true");
        // Allows the http://www.xxx.com domain (set by itself, as an example) to make cross-domain requests
        res.addHeader("Access-Control-Allow-Origin"."*");
        // Set the method to allow cross-domain requests
        res.addHeader("Access-Control-Allow-Methods"."GET, POST, DELETE, PUT");
        // Allow cross-domain requests to contain content-Type
        res.addHeader("Access-Control-Allow-Headers"."Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }
    
    @Override
    public void destroy() {
    }
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
Copy the code

Well, Springboot is more commonly used to solve cross-domain problems have been shared with you, I hope to help the old iron.

From: chensj.blog.csdn.net/article/det…