关于CORS的设置,其实是一个很简单的问题,如果不使用security的复杂配置,采用WebMvcConfigurer即可。但在Security的配置下, 浏览器对CORS的验证变得稍微复杂了一些,Chat了一通之后,大致理清楚如下:
- 浏览器首先会发送一个OPTIONS请求去确认后端是否支持CORS
- 后端必须先响应这个请求才能让浏览器继续继续发送访问请求
在需要JWT、Session等authenticated 的接口中,如果后端对OPTIONS请求未做放行处理,则会报错误:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
看上去像是CORS没设置对,其实是OPTIONS请求因为需要authenticate被拒绝了。
得出结论,修改方案如下:
- 在CorConfig里面添加OPTIONS方法
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(org.springframework.web.servlet.config.annotation.CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "OPTIONS")
.allowedHeaders("Authorization", "Content-Type")
.allowCredentials(true)
.maxAge(3600);
}
}
- 对所有OPTIONS请求放行
http.authorizeRequests(auth->auth.requestMatchers(HttpMethod.OPTIONS, "/api/*").permitAll())
...
http.cors(Customizer.withDefaults()); //让自定义的CorsConfig生效。