Springboot CORS cross-domain access

What is cross-domain

The same origin policy of the browser: It is the core and most basic security function of the browser. If the same origin policy is absent, the normal functions of the browser may be affected. The Web is built on the same origin policy, and browsers are just an implementation of the same origin policy. The same origin policy prevents javascript scripts in one domain from interacting with content in another domain. Same-origin (that is, in the same domain) means that two pages have the same protocol, host, and port.

When the protocol, domain name, or port of a URL request is different from the current page URL, it is called cross-domain

For example:

Current page URL Url of the requested page ** Whether to cross-domain ** why
www.test.com/ www.test.com/index.html no Same-origin (same protocol, domain name, and port number)
www.test.com/ www.test.com/index.html Cross domain Different protocols (HTTP/HTTPS)
www.test.com/ www.baidu.com/ Cross domain Different master domain name (test/baidu)
www.test.com/ blog.test.com/ Cross domain Different subdomains (WWW /blog)
www.test.com:8080/ www.test.com:7001/ Cross domain Different port numbers (8080/7001)

Cross-domain constraints

[1] Cookies, LocalStorage and IndexedDB of non-same-origin web pages cannot be read

[2] DOM of non-homologous web pages cannot be accessed

[3] Unable to send AJAX requests to non-homologous addresses

Build CORS cross-domain access based on Springboot

Build cross-domain resource server that can be accessed by off-site Ajax request based on SpringBooot project.

Method one:

Add @crossorigin to each controller

Where the 2 parameters in @crossorigin:

Origins: Specifies the list of domains that can be accessed

MaxAge: Maximum cache duration (in seconds) before a response is prepared.

Without the @ CrossOrigin:

@RestController @RequestMapping("/test") public class TestRequestLogController { @RequestMapping("/request_log") public String TestRequestLog(@RequestParam String name){ return "hello " + name; }}Copy the code

Add @ CrossOrigin:

Method 2:

@Configuration public class CorsConfig { private CorsConfiguration corsConfiguration(){ CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod(HttpMethod.GET); corsConfiguration.addAllowedMethod(HttpMethod.POST); corsConfiguration.addAllowedOrigin("*"); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration()); return new CorsFilter(urlBasedCorsConfigurationSource); }}Copy the code