【发布时间】:2017-03-05 07:33:59
【问题描述】:
我目前正在使用 Auth0(和 Angular 2 GUI),它将请求中的 "x-xsrf-token" 类型的标头发送到 Spring Boot API。
我得到错误:
"XMLHttpRequest 无法加载http://localhost:3001/ping。请求头 Access-Control-Allow-Headers 中的字段 x-xsrf-token 不允许 预检响应。”
这很公平,因为 Response Headers 中的 Access-Control-Response-Headers 列表不包括 x-xsrf-token(在 Chrome 的网络选项卡中调试请求时)。
我尝试了很多解决方案,我想我最接近的是覆盖AppConfig中的configure方法,并添加我自己的CorsFilter,如下所示:
(Imports removed for brevity)
@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class AppConfig extends Auth0SecurityConfig {
@Bean
public Auth0Client auth0Client() {
return new Auth0Client(clientId, issuer);
}
@Bean
public Filter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("Content-Type");
config.addAllowedHeader("x-xsrf-token");
config.addAllowedHeader("Authorization");
config.addAllowedHeader("Access-Control-Allow-Headers");
config.addAllowedHeader("Origin");
config.addAllowedHeader("Accept");
config.addAllowedHeader("X-Requested-With");
config.addAllowedHeader("Access-Control-Request-Method");
config.addAllowedHeader("Access-Control-Request-Headers");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Override
protected void authorizeRequests(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/ping").permitAll().antMatchers("/").permitAll().anyRequest()
.authenticated();
}
String getAuthorityStrategy() {
return super.authorityStrategy;
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf().disable();
http.addFilterAfter(auth0AuthenticationFilter(auth0AuthenticationEntryPoint()),
SecurityContextPersistenceFilter.class)
.addFilterBefore(simpleCORSFilter(), Auth0AuthenticationFilter.class);
authorizeRequests(http);http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.cors();
}
}
不幸的是,我没有成功,并且仍然看到我的 get 请求的响应标头中缺少 x-xsrf-token。
我的基础项目是这样的: https://github.com/auth0-samples/auth0-spring-security-api-sample/tree/master/01-Authentication/src/main
欢迎提出任何想法。
【问题讨论】: