我无法在Spring Boot Security中使用CORS使HTTP正常工作 . 我已经在网络和StackOverFlow上搜索并尝试了不同的解决方案,但我已经达到了一个我不知道该怎么办的地步 .
我不断从Angular FrontEnd应用程序(Firefox)收到此错误:来自另一个被阻止的源的请求:相同的源策略阻止在http://172.20.3.9:8080/api/auth/signin读取远程资源(原因:缺少CORS头'Access-Control-Allow-Origin') . [了解更多]跨源阻止请求:同一原始策略不允许在http://172.20.3.9:8080/api/auth/signin读取远程资源 . (原因:CORS请求没有成功) .
我有一个Bean定义来在我的Tomcat中实现HTTPs重定向,如下所示:
@Bean
public TomcatServletWebServerFactory servletContainer(){
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(redirectConnector());
return tomcat;
}
private Connector redirectConnector(){
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8444);
return connector;
}
我还有一个WebSecurity类,使用我的CORS过滤器扩展WebSecurityConfigurerAdapter并覆盖配置
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
这种方法现在简化了 . 我测试了很多配置:有/没有.cors(),channelSecure等等 .
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests().antMatchers("/api/auth/**")
.permitAll()
http.addFilterBefore(corsFilter(), ChannelProcessingFilter.class);
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
我还尝试在控制器/方法中定义@CrossOrigin . 我没有HTTPs重定向的当前配置方法工作正常,没有CORS问题:
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/auth/**")
.permitAll()
.anyRequest().anonymous();
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
所以我想问题是Spring Security和Tomcat中的HTTPS Redirect的结合 . 有人可以帮我解决这个问题吗?提前致谢,
1 回答
您需要做的就是创建以下类