springboot跨域配置不必多说,网上很多:
首先配置好,我用的是继承WebMvcConfigurer配置,还可以通过过滤器配置,我觉得这样应该是最方便了,缺点就是这种配置不能在interceptor中再配置header。
@Configuration
public class MyWebConfigurer implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addCorsMappings(CorsRegistry registry) {
//所有请求都允许跨域,使用这种配置方法就不能在 interceptor 中再配置 header 了
registry.addMapping("/**")
.allowCredentials(true)
.allowedOrigins("http://localhost:8080")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.allowedHeaders("*")
.maxAge(3600);
}
}
接着是配置springsecurity:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf() //其他代码略,这里只贴出跨域必要的代码
}
查看源码就能发现.csrf()是通过CorsConfigurationSource去配置的,所以我们要重新注入一个bean,
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
configuration.setAllowedMethods(Arrays.asList("POST", "GET", "PUT", "OPTIONS", "DELETE"));
configuration.setAllowCredentials(true);
configuration.applyPermitDefaultValues();
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
其中把博主倒弄了半天的就是这一行代码:
configuration.setAllowCredentials(true);
如果不加上,跨域请求时会出现错误:
The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’.
博主原本还以为是springboot配置跨域时出的问题,后来认真测试了一番才得出结果,希望对各位有帮助。