我正在尝试在已经设置了基本身份验证的Spring启动应用程序中配置CORS .
我在许多地方进行过搜索,包括this answer,在官方文档中指出Filter based CORS support .
到目前为止没有运气 .
我的AJAX请求是这样完成的 . 如果从同一个来源http://localhost:8080完成它 .
fetch('http://localhost:8080/api/lists', {
headers: {
'Authorization': 'Basic dXNlckB0ZXN0LmNvbToxMjM0NQ=='
}
}
AJAX请求是在http://localhost:3000的React应用程序中完成的,所以我尝试了以下Spring启动CORS配置:
@Configuration
class MyConfiguration {
@Bean
public FilterRegistrationBean corsFilter()
{
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
// Maybe I can just say "*" for methods and headers
// I just copied these lists from another Dropwizard project
config.setAllowedMethods(Arrays.asList("GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD"));
config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept",
"Authorization", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods",
"Access-Control-Allow-Origin", "Access-Control-Expose-Headers", "Access-Control-Max-Age",
"Access-Control-Request-Headers", "Access-Control-Request-Method", "Age", "Allow", "Alternates",
"Content-Range", "Content-Disposition", "Content-Description"));
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
我的WebSecurityConfig:
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and()
.authorizeRequests()
.antMatchers("/", "/index.html").permitAll()
.anyRequest().fullyAuthenticated();
}
}
来自http://localhost:3000的 fetch
调用在控制台中显示此401错误:
Fetch API无法加载http:// localhost:8080 / api / lists . 预检的响应具有无效的HTTP状态代码401 .
在chrome dev工具的网络选项卡中,我看到了这个OPTIONS请求:
2 回答
我认为你需要允许
OPTION
请求进入你的网络安全配置 . 就像是:.antMatchers(HttpMethod.OPTIONS, "/your-url").permitAll()
试试这个: