预检的响应具有无效的HTTP状态代码401 – Spring

大家。 我是Angular 2和Spring Framework的新手。 我正在尝试使用授权标头(基本身份validation)的简单获取请求。

我正在使用Spring Boot(1.2.6.RELEASE),这也是相关的。 我的CORS配置如下所示。

@Component public class SimpleCorsFilter implements Filter { private final Logger log = LoggerFactory.getLogger(SimpleCorsFilter.class); public SimpleCorsFilter() { log.info("SimpleCORSFilter init"); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, authorization, x-auth-token"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } } 

这就是客户端的样子

  this.headers.append('Authorization', 'Basic dXNlcjphZG1pbg=='); return this.http .get(`http://localhost:8080/api/login?username=${username}`, {headers : this.headers} ) .map(response => response.json().data as any); } 

我一直在:

XMLHttpRequest无法加载http:// localhost:8080 / api / login?username = user 。 预检的响应具有无效的HTTP状态代码401

请帮助,我不知道我错过了什么……我已经检查了很多post但是无法到达那里……

当http方法为OPTIONS时,避免过滤并设置状态200

 if("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } 

如果有人遇到类似的情况,使用Spring Boot,Spring Security和像angular 2/4这样的客户,我在这里发布了调查结果 。

对于那些正在寻找简短答案的人,你必须配置两件事:

  1. 使用Spring Boot,启用全局CORS的推荐方法是在Spring MVC中声明并结合细粒度的@CrossOrigin配置:

     @Configuration public class CorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*") .allowedHeaders("*"); } }; } } 
  2. 然后,在使用Spring Security时,您必须在Spring Security级别启用CORS,以允许它利用Spring MVC级别定义的配置:

     @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and()... } } 

干杯!!!

这可能是非常晚的,但这可以解决一些问题,经过长时间我找到了答案

 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure( WebSecurity web ) throws Exception { web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" ); } } 

请参阅https://stackoverflow.com/a/45830981/3724760

弹簧安全指南中的另一个选项:

在安全配置类中,它扩展了WebSecurityConfigurerAdapter配置cors()

  protected void configure(HttpSecurity http) throws Exception { http .cors().and().**this will use corsConfigurationSource by** default. so lets define corsConfigurationSource // other criteria } **so lets define corsConfigurationSource** @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://myufrontend.com")); configuration.setAllowedMethods(Arrays.asList("GET", "POST")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); }