使用Spring Security在后端启用CORS的正确方法是什么?在REST框架的项目中也使用Apache cxf

时间:2019-01-10 18:05:45

标签: spring rest spring-security cors cxf

我有以下代码片段(以及其他一些配置)。还应该做些什么? chrome的错误是: “对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。”

SC: Screenshot for ResponseHeaders from the page to which rxjs(Using angular) call is made

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
protected  class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .cors().and()
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS,"/oauth/token").permitAll();
    }
@Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    protected CorsConfigurationSource corsConfigurationSource()
    {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.setMaxAge((long) 3600);
        configuration.addAllowedOrigin("*");
        //configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        //configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS", "DELETE"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        //configuration.setAllowedHeaders(Arrays.asList( "x-requested-with","X-requested-with", "authorization", "cache-control", "Content-Type,adminUserId"));
        configuration.setExposedHeaders(Arrays.asList("Access-Control-Allow-Origin","Access-Control-Allow-Credentials"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);

        return source;
    }
}
@Configuration
@EnableResourceServer
protected class ResourceServer extends ResourceServerConfigurerAdapter {

    @Autowired
    @Qualifier("dataSource")
    DataSource dataSource;

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {         
        http
        .anonymous().disable()
        .requestMatchers().antMatchers("/rest/services/messagePosting/**")
        .and().authorizeRequests()
        .antMatchers("/rest/services/messagePosting/**")
        .authenticated()
        .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());     
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources)
            throws Exception {
        resources.resourceId("my-rest-services");
    }
}

1 个答案:

答案 0 :(得分:-1)

更新:此解决方案仅适用于Spring-boot。
无法回忆确切的情况,但是我猜想是在OAuth2配置中,当我在扩展WebSecurityConfigurerAdapter的配置类中配置CORS时遇到了类似的问题,但这没有帮助。
我发现的解决方案是在单独的Java类中配置CORS,然后将该类导入到Spring安全配置类中。如下所示:

@Configuration
public class CorsConfig {   

    @Bean
    public FilterRegistrationBean<Filter> customCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<Filter>(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

您的安全配置类(请注意导入注释):

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
@Import({CorsConfig.class})
protected  class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .cors().and()
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS,"/oauth/token").permitAll();
    }