Three methods for SpringBoot to handle CORS cross-domain requests

1 Introduction

Springboot cross-domain issues are a difficult problem that current mainstream web developers cannot avoid. But we must first make it clear that the following points
cross-domain only exist on the browser side , and do not exist in other environments such as Android/ios/Node.js/python/java.
Cross-domain requests can be sent out, and the server can receive the request and return normally. As a result, only the results were intercepted by the browser.
The reason why it occurs across domains is that it is restricted by the same-origin policy. The same-origin policy requires that the source is the same for normal communication, that is, the protocol, domain name, and port number are all exactly the same.
For security reasons, browsers must comply with the same-origin policy when using the XMLHttpRequest object to initiate HTTP requests. Otherwise, it will be a cross-domain HTTP request, which is 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 interact with resources from another source. This is an important security mechanism for isolating potentially malicious files.

2 What is CORS?

CORS is a W3C standard, whose full name is "Cross-origin resource sharing", which allows browsers to issue XMLHttpRequest requests to cross-origin servers, thereby overcoming the limitation that AJAX can only be used from the same source.
It adds a special Header [Access-Control-Allow-Origin] to the server to tell the client about cross-domain restrictions. If the browser supports CORS and determines that the Origin is passed, XMLHttpRequest will be allowed to initiate cross-domain requests.

CORS Header

  • Access-Control-Allow-Origin: http://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

Insert image description here

3 SpringBoot cross-domain request processing methods

3.1 Method 1: Directly use SpringBoot’s annotation @CrossOrigin (SpringMVC is also supported)

In a simple and crude way, the Controller layer can add this annotation to the classes or methods that need to cross domains.

@RestController
@CrossOrigin
@RequestMapping("/situation")
public class SituationController extends PublicUtilController {
    
    
    @Autowired
    private SituationService situationService;
    // log日志信息
    private static Logger LOGGER = Logger.getLogger(SituationController.class);
}

But each Controller has to be added, which is too troublesome. What should I do? Just add it to the public parent class of Controller (PublicUtilController) and all Controllers can inherit it.

@CrossOrigin
public class PublicUtilController {
    
    
    /**
     * 公共分页参数整理接口
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    public PageInfoUtil proccedPageInfo(String currentPage, String pageSize) {
    
    
        /* 分页 */
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        try {
    
    
            /*
             * 将字符串转换成整数,有风险, 字符串为a,转换不成整数
             */
            pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
            pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
        } catch (NumberFormatException e) {
    
    
        }
        return pageInfoUtil;
    }
}

Of course, although this refers to SpringBoot, SpringMVC is the same, but it requires Spring 4.2 and above. In addition, if the SpringMVC framework version is inconvenient to modify, you can also modify tomcat's web.xml configuration file to handle
SpringMVC using @CrossOrigin. The usage scenario requires
jdk1.8+
Spring4.2+

3.2 Method 2, Configuration for handling cross-domain requests

Add a configuration class, CrossOriginConfig.java. Inherit WebMvcConfigurerAdapter or implement the WebMvcConfigurer interface. Don't worry about anything else. When the project starts, the configuration will be read automatically.

@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);
    }
}

3.3 Method 3, using filter

In the same way as the second method, add a configuration class, add a CORSFilter class, and implement the Filter interface. Don't worry about anything else. When the interface is called, cross-domain interception will be filtered.

@Component
public class CORSFilter implements Filter {
    
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
    
    
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        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 {
    
    
    }
}

4 Summary

Okay, I have shared with you the more commonly used methods of solving cross-domain problems in Springboot. I hope it will be helpful to you.

Guess you like

Origin blog.csdn.net/weixin_44030143/article/details/130782491
Recommended