首页 > 解决方案 > CORS 错误 - Spring Boot 安全性 + HTTPS 重定向

问题描述

我无法使 HTTPs 在 Spring Boot Security 中与 CORS 一起正常工作。我已经在网络和 StackOverFlow 上搜索并尝试了不同的解决方案,但我已经到了不知道该怎么做的地步。

我不断从 Angular FrontEnd 应用程序 (Firefox) 收到此错误: 来自另一个被阻止源的请求:相同的源策略阻止读取http://172.20.3.9:8080/api/auth/signin上的远程资源(原因:CORS缺少标头“访问控制允许来源”)。[了解更多] 跨域阻塞请求:同源策略不允许在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 重定向的结合。有人可以帮我解决这个问题吗?提前致谢,

标签: spring-bootspring-securityhttpscors

解决方案


您需要做的就是创建以下类

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*");
    }
}

推荐阅读