如何在Sping Boot + Spring Security上禁用CORS

qvk1mo1f  于 2023-08-05  发布在  Spring
关注(0)|答案(1)|浏览(285)

我有一个spring Boot rest应用程序,可以通过https.dummy.cs访问。我的应用程序的spring Boot starter父版本是2.7.6。我在我的应用程序中添加了Spring安全依赖项来保护端点。我有一个angular应用程序(部署在http://localhost:4200上),它试图连接到https://dev.dummy.cs,在我的浏览器中显示以下错误:

Access to XMLHttpRequest at https.dummy.cs from origin http://locahost has been blocked by cors policy

字符串
我尝试在Spring中禁用cors策略,如下所示:

@Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        //@formatter:off
        httpSecurity
                .httpBasic().disable()
                .csrf().disable().exceptionHandling().authenticationEntryPoint(sHandler);

        httpSecurity.cors().disable().
                
                antMatchers(ATT_WHITELIST).permitAll().
                anyRequest().authenticated();// whitelist Swagger UI resources
    

  ..
        httpSecurity.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        return httpSecurity.build();
    }


我还添加了如下配置:

@Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins("dev.dummy.cs,https://dev.dummy.cs");
        config.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT"));
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return source;
    }


任何人都可以指出我在这里错过了什么,请,因为我得到了cors错误?

xnifntxz

xnifntxz1#

根据documentationsetAllowedOrigins定义为public void setAllowedOrigins(@Nullable List<String> origins)!然而,您没有传递List<String>,而是在String中传递List。因此,请将config.setAllowedOrigins("dev.dummy.cs,https://dev.dummy.cs");更改为config.setAllowedOrigins("dev.dummy.cs", "https://dev.dummy.cs");
此外,您还通过httpSecurity.cors().disable()停用了CORS配置。为了激活我们之前定义的CORS配置,您必须在httpSecurity中将其更改为.and().cors()

相关问题