java - 使用 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
}
}
解决方案
使用config.setAllowedOriginPatterns("*")
代替config.setAllowedOrigins(Collections.singletonList("*"));
推荐阅读
- matlab - Matlab 编辑器变得非常慢,多项式方程具有“组合”(大量)项
- reactjs - 在 ReactJs 中使用 props 访问对象
- android - 颤振 - 重新加载时奖励视频广告错误:“ad_not_loaded,奖励视频显示失败,未加载广告,null)”
- r - R熔化/收集文件,带有2个标题行到属性中
- ruby - 使用 Hash 中的键值对作为问答
- scheme - 方案中的 Luhn 算法
- c++ - 如何计算 eigen::Tensor 中非零的数量
- reactjs - “react-dnd”不包含名为“DragDropContext”的导出
- python - pandas dataframe - 从特定条件下获取价值
- mongodb - 创建 mongodb 数据库并通过 docker-compose 填充一些数据