为 CORS 配置 Spring

我正在尝试为 CORS 配置 Spring 以使用 Angular Web UI:


我试过这个:


@Configuration

@ComponentScan("org.datalis.admin.config")

public class AppConfig {


    @Bean

    public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {

        PropertySourcesPlaceholderConfigurer conf = new PropertySourcesPlaceholderConfigurer();

        conf.setLocation(new ClassPathResource("application.properties"));

        return conf;

    }


    @Bean

    public FilterRegistrationBean<CorsFilter> corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true);

        config.addAllowedOrigin("127.0.0.1");

        config.addAllowedHeader("*");

        config.addAllowedMethod("*");

        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));

        bean.setOrder(0);

        return bean;

    }

}

带有 Angular FE 的 Apache 服务器与 Wildly 服务器在同一台服务器上运行,因此我为源配置了 127.0.0.1。


但我仍然得到:


Access to XMLHttpRequest at 'http://123.123.123.123:8080/api/oauth/token' from origin 'http://123.123.123.123' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

auth:1 Failed to load resource: the server responded with a status of 404 (Not Found)

你知道我该如何解决这个问题吗?


芜湖不芜
浏览 115回答 3
3回答

森林海

您允许的来源是 127.0.0.1,但您的客户端具有 ip 123.123.123.123。尝试改变这一点:config.addAllowedOrigin("127.0.0.1");对此:config.addAllowedOrigin("123.123.123.123");

呼啦一阵风

您需要告诉Spring Security使用您创建的 CORS 配置。在我的项目中,我Spring Security以这种方式配置:@Overrideprotected void configure(HttpSecurity http) throws Exception{&nbsp; &nbsp; http&nbsp; &nbsp; &nbsp; &nbsp; .authorizeRequests()&nbsp; &nbsp; &nbsp; &nbsp; .antMatchers("/rest/protected/**")&nbsp; &nbsp; &nbsp; &nbsp; .authenticated()&nbsp; &nbsp; &nbsp;//Other spring sec configruation and then:&nbsp; &nbsp; .and()&nbsp; &nbsp; &nbsp; &nbsp; .cors()&nbsp; &nbsp; &nbsp; &nbsp; .configurationSource(corsConfigurationSource())}在哪里corsConfigurationSource():@Bean&nbsp; &nbsp; CorsConfigurationSource corsConfigurationSource() {&nbsp; &nbsp; &nbsp; &nbsp; UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();&nbsp; &nbsp; &nbsp; &nbsp; boolean abilitaCors = new Boolean(env.getProperty("templating.oauth.enable.cors"));&nbsp; &nbsp; &nbsp; &nbsp; if( abilitaCors )&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( logger.isWarnEnabled() )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logger.warn("CORS ABILITATI! Si assume ambiente di sviluppo");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CorsConfiguration configuration = new CorsConfiguration();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200","http://localhost:8080", "http://localhost:8180"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; configuration.setAllowedMethods(Arrays.asList(&nbsp; RequestMethod.GET.name(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RequestMethod.POST.name(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RequestMethod.OPTIONS.name(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RequestMethod.DELETE.name(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RequestMethod.PUT.name()));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; configuration.setExposedHeaders(Arrays.asList("x-auth-token", "x-requested-with", "x-xsrf-token"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; configuration.setAllowedHeaders(Arrays.asList("X-Auth-Token","x-auth-token", "x-requested-with", "x-xsrf-token"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; source.registerCorsConfiguration("/**", configuration);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return source;&nbsp; &nbsp; }

MM们

这是我@Configuration处理仅在开发环境中使用的 CORS 请求的工作班。@Configuration//@Profile(PROFILE_DEV)&nbsp; public class CorsConfiguration {&nbsp; @Bean&nbsp; public WebMvcConfigurer corsConfigurer() {&nbsp; &nbsp; &nbsp; return new WebMvcConfigurer() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void addCorsMappings(CorsRegistry registry) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; registry.addMapping("/**")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .allowedOrigins("*")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .allowedHeaders("*")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .allowedMethods("*");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; };&nbsp; }}您还必须配置 Spring Security 以忽略HttpMethod.OPTIONS预检请求使用的(作为您提到的例外)@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)public class SecurityConfiguration extends WebSecurityConfigurerAdapter {&nbsp; //...&nbsp; &nbsp; @Override&nbsp; &nbsp; public void configure(WebSecurity web) throws Exception {&nbsp; &nbsp; &nbsp; web.ignoring()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //others if you need&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .antMatchers(HttpMethod.OPTIONS, "/**");&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void configure(HttpSecurity http) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; http&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .csrf()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .disable()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .exceptionHandling()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .and()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .headers()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .frameOptions()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .disable()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .and()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .authorizeRequests()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .antMatchers("/api/register").permitAll()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .antMatchers("/api/activate").permitAll()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .antMatchers("/api/authenticate").permitAll()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .antMatchers("/api/**").authenticated();&nbsp; &nbsp; }}因为当您使用 cors 时,您有触发一个简单请求和预检请求HttpMethod.OPTIONS
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java