1. CORS support based on filters (Spring Boot project)
The Spring framework also provides CorsFilter. In this case, do not use @CrossOrigin
or WebMvcConfigurer#addCorsMappings(CorsRegistry)
, for example, you can declare the following filter in the Spring Boot application:
package com.card.config;
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;
/**
* 跨域访问控制
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许任何域名使用
corsConfiguration.addAllowedOrigin("*");
// 允许任何头
corsConfiguration.addAllowedHeader("*");
// 允许任何方法(post、get等)
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 对接口配置跨域设置
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
Two, Nginx way
1. Download Nginx (1.18.0 recommended)
https://nginx.org/en/download.html
2. Configure Nginx, edit nginx-1.18.0\conf\nginx.conf
Comment out the default server configuration
server{
listen 80;
server_name localhost;
location /{
proxy_pass http://192.168.0.76:8005/;
}
location /ssns-serve{
proxy_pass http://localhost:8080;
}
}
The above code means to localhost:80
forward as 192.168.0.76:8005
, that is to say, the visit is localhost:80
actually a visit 192.168.0.76:8005
, and the visit localhost:80/ssns-serve
is a visit localhost:8080
, and ssns-serve
starts with a url
3. Cross-domain (CORS) support:
Spring Framework 4.2 GA provides first-class support for CORS, making it easier and more powerful to configure it than the usual filter-based solutions. So the version of springMVC must be 4.2 or above to support @CrossOrigin
1. The controller configures CORS
1.1. CORS configuration of the controller method, you can add a @CrossOrigin annotation to the @RequestMapping annotation handler method to enable CORS (by default, @CrossOrigin allows all sources and HTTP methods specified in the @RequestMapping annotation)
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
Among them are the 2 parameters in @CrossOrigin:
origins : the list of domains that are allowed to be accessed
maxAge : the maximum time (in seconds) that the cache lasts before preparing a response
1.2. Enable @CrossOrigin for the entire controller
@CrossOrigin(origins = "http://baidu.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
1.3. Using both controller and method level CORS configuration, Spring will merge the two annotation attributes to create a merged CORS configuration
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin(origins = "http://baidu.com")
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
1.4. If you are using Spring Security, make sure to enable CORS at the Spring security level and allow it to take advantage of the configuration defined at the Spring MVC level
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
2. Global CORS configuration
In addition to fine-grained, annotation-based configuration, you may also need to define some global CORS configurations. This is similar to using filters, but can be declared as Spring MVC and combined with fine-grained @CrossOrigin configuration. By default, all origins and GET, HEAD and POST methods are allowed
JavaConfig
simplifies the CORS of the entire application to:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
If you are using Spring Boot, it is recommended to declare the WebMvcConfigurer bean as follows:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
You can easily change any attribute and apply this CORS configuration only to specific path patterns:
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://baidu.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
If you are using Spring Security, make sure to enable CORS at the Spring security level and allow it to take advantage of the configuration defined at the Spring MVC level
PS: The reason why Spring annotation @CrossOrigin does not work
1. The version of springMVC must be 4.2 or above to support @CrossOrigin
2. Non-@CrossOrigin does not solve the cross-domain request problem, but incorrect requests result in the failure to get the expected response, which leads to the browser prompting cross-domain problems
3 , After adding @CrossOrigin annotation above the Controller annotation, cross-domain problems still occur. One of the solutions is:
the Get and Post methods are not specified in the @RequestMapping annotation. After the specific designation, the problem is solved
code show as below:
@CrossOrigin
@RestController
public class person{
@RequestMapping(method = RequestMethod.GET)
public String add() {
// ...
}
}