【发布时间】:2017-04-25 20:14:03
【问题描述】:
我正在尝试在已设置基本身份验证的 Spring Boot 应用程序中配置 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 boot 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;
}
}
我的网络安全配置:
@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 开发工具的网络选项卡中,我看到了这个 OPTIONS 请求:
【问题讨论】:
标签: ajax security spring-boot cors basic-authentication