Spring Boot - React 无法授权过滤器调用

ncg*_*r99 5 spring servlets spring-security reactjs spring-boot

大家好,我是 Spring Boot 和 React 的新手,我正在使用React JS 和 Spring Boot 开发简单的登录应用程序,每当我尝试导航到不同的 API 调用(例如注销、欢迎)时,我都会收到以下消息 Failed授权带有属性 [authenticated] 的过滤器调用 [GET /welcome] 我认为这是 WebSecurityConfigurerAdapter 寻找正确解决方案的事情

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable().sessionManagement().sessionFixation().migrateSession().and()
            //.addFilterAfter(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).csrf().disable()
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .anyRequest().authenticated()
            .and().formLogin().loginPage("/login").and()
            .logout()
            .logoutUrl("/logout").invalidateHttpSession(true).deleteCookies().clearAuthentication(true)
            .permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/403").and().httpBasic();
}
Run Code Online (Sandbox Code Playgroud)

处理仪表板(){

axios.get("http://localhost:8080/welcome",{ withCredentials: true }).then(res => {
  if (res.data === "success") {
    this.props.history.push("/");
  } else {
    alert("Authentication failure");
  }
});
Run Code Online (Sandbox Code Playgroud)

}

WebSecurityConfig 日志输出

ncg*_*r99 2

在尝试了 spring security 和 spring boot 之后,我能够找到根本原因并修复它,只需在主类文件(全局 CORS 配置)中启用 CORS 即可修复上述问题。

ps: 即使在方法级别启用 CORS 也无法正确识别,需要在主类中添加它

  @Bean
public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
    config.setAllowedMethods(Collections.singletonList("*"));
    config.setAllowedHeaders(Collections.singletonList("*"));
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}
Run Code Online (Sandbox Code Playgroud)