gpt4 book ai didi

java - 使用 CorsFilter 和 spring security 时出现 Cors 错误

转载 作者:行者123 更新时间:2023-12-03 21:43:23 24 4
gpt4 key购买 nike

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

java.lang.IllegalArgumentException: When allowCredentials is true,allowedOrigins cannot contain the special value "*"since that cannotbe set on the "Access-Control-Allow-Origin" response header. To allowcredentials to a set of origins, list them explicitly or considerusing "allowedOriginPatterns" instead.


我试图找到 的例子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("*"));

关于java - 使用 CorsFilter 和 spring security 时出现 Cors 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66060750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com