On cross domain configuration of springboot2.4
- 2021-11-02 00:58:36
- OfStack
1. If it is just a simple springboot demo, just use the following configuration
Create a new config class
```
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author yk
* @date 2021/7/19 14:36
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.maxAge(3600)
.allowCredentials(true);
}
}
```
2. However, in actual development, we need to combine spring-security, oauth2, etc., and we will find that the above configuration is invalid, because the priority of the previous Filter is too high, so we can adopt the following configuration
```
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author yk
* @date 2021/7/19 16:21
*/
@Configuration
public class CrosConfig {
@Bean
public FilterRegistrationBean corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
// Setting the highest priority here
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}