首页 > 解决方案 > 使用 CorsFilter 和 spring security 时出现 Cors 错误

问题描述

我正在使用 Spring Boot 构建 API 服务。它使用基本身份验证进行身份验证。当客户端尝试连接到 API 时,他们会收到CORS 错误

在 Spring Boot 上,它会引发错误

java.lang.IllegalArgumentException:当allowCredentials 为真时,allowedOrigins 不能包含特殊值“*”,因为它不能在“Access-Control-Allow-Origin”响应标头上设置。要允许一组来源的凭据,请明确列出它们或考虑改用“allowedOriginPatterns”。

我试图找到allowedOriginPatterns用法的示例,但尚未找到。即使对于它的文档-https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/CorsRegistration.html#allowedOriginPatterns-java.lang.String ...我仍然不知道我必须在config.allowedOriginPatterns(); 中放入什么模式;

下面是我的 CorsFilter 代码,

@Configuration
public class RequestCorsFilter {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOrigins(Collections.singletonList("*"));
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "responseType", "Authorization"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }      

}

这是我的身份验证代码,

@Configuration
@EnableWebSecurity
public class AuthenConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
        throws Exception {
    auth
    .inMemoryAuthentication()
    .withUser("thor").password("{noop}P@ssw00rd")
    .authorities("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
        };

        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers(AUTH_WHITELIST).permitAll() // whitelist URL permitted
            .antMatchers("/api").authenticated(); // others need auth
    }

}

标签: javaspringspring-boot

解决方案


使用config.setAllowedOriginPatterns("*")代替config.setAllowedOrigins(Collections.singletonList("*"));


推荐阅读