该问题通常出现在使用Spring Security配置跨域访问时。该错误表明,在对alloweOriginPatterns属性进行设置时,存在不合法的参数。
解决此问题的方法是通过正则表达式对alloweOriginPatterns属性进行合法性验证。以下是一个代码示例:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(corsConfigurationSource());
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("*"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
// 正则表达式验证
String allowedOriginPatterns = "https://.*\\.example\\.com";
if (!Pattern.matches("^https?://.*$|^\\*$/", allowedOriginPatterns)) {
throw new IllegalArgumentException("allowedOriginPatterns is illegal!");
}
config.setAllowedOriginPatterns(Arrays.asList(allowedOriginPatterns));
return source;
}
}