【发布时间】:2021-05-29 06:45:53
【问题描述】:
正如标题所述,我有一个 Spring Boot 后端,它为 React 前端提供 REST API。我遇到了许多 CORS 问题,并尝试了多种方法。我不是 spring-security 方面的专家,但非常感谢解决这个问题的一些帮助。
我的 CORS 配置
private static final String [] AUTH_WHITELIST = {
// -- Swagger UI v2
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
"/_ah/warmup",
"/ae/test",
// -- Swagger UI v3 (OpenAPI)
"/v3/api-docs/**",
"/swagger-ui/**",
// other public endpoints of your API may be appended to this array
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().configurationSource(corsConfigurationSource()).and().authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers(AUTH_WHITELIST).permitAll()
.anyRequest().authenticated();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider,userDetailsService));
}
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
//config.setAllowedOriginPatterns(Arrays.asList("/*"));
config.setAllowedOrigins(Arrays.asList("localhost:3000"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("*"));
config.setAllowCredentials(false);
source.registerCorsConfiguration("/**", config);
return source;
}
【问题讨论】:
标签: spring spring-boot rest web cors