【问题标题】:Spring Boot - React Failed to authorize filter invocationSpring Boot - React 无法授权过滤器调用
【发布时间】:2021-05-28 02:22:14
【问题描述】:

大家好,我是 spring boot 和 react 的新手,我正在开发简单的登录应用程序使用 react js 和 spring boot, 每当我尝试导航到不同的 API 调用(例如注销、欢迎)时,我都会收到以下消息 无法使用属性 [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();
}

handleDashboard() {

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

}

WebSecurityConfig log output

【问题讨论】:

    标签: reactjs spring spring-boot servlets spring-security


    【解决方案1】:

    在玩过 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 2019-02-10
      • 2019-01-04
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多