【发布时间】:2020-02-26 17:18:16
【问题描述】:
我正在尝试配置 Spring Security 以使其支持 CORS。 感谢这篇文章 Spring security CORS Filter,我已经使用 Spring Boot 使用此配置代码在我的本地主机上运行它:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.antMatcher("/api/**")
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/login").permitAll()
.antMatchers(HttpMethod.GET, "/api/websocket/**").permitAll()
.antMatchers("/api/**").authenticated()
.and()
.addFilterBefore(new JWTLoginFilter("/api/login", HttpMethod.POST, authenticationManager(), tokenAuthenticationService, myUserService), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class)
.csrf().disable();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.of("HEAD",
"GET", "POST", "PUT", "DELETE", "PATCH"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
但是当我在远程 Tomcat 服务器上部署我的应用程序时,它不起作用:
Access to XMLHttpRequest at 'http://xxx:9080/yyy/api/user/findByLogin/?login=zzz' from origin 'http://xxx:10080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我的配置类是否足够,或者我需要在 Tomcat 设置中进行设置吗? 谢谢
【问题讨论】:
-
你能检查一下你的 OPTIONS 请求是否给出了 CORS 错误吗?如果是这样,请将其添加到您允许的方法中,然后重试。
-
OPTIONS 请求返回 403。我添加了屏幕截图。
-
你能看看这篇文章吗? stackoverflow.com/questions/43699343/…
-
同理,解决方案在本地有效,在Tomcat上无效。
-
你的 pom.xml 和 main 类是什么样子的?请尝试提供minimal reproducible example。