【发布时间】:2021-05-09 15:30:33
【问题描述】:
我正在使用 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
}
}
【问题讨论】:
标签: java spring spring-boot