Issue
Hi all I'm new to spring boot and react, I'm working on the simple login app using react js and spring boot, whenever I try to navigate to a different API call (e.g logout, welcome) I get the following message Failed to authorize filter invocation [GET /welcome] with attributes [authenticated] I think this is something with WebSecurityConfigurerAdapter looking for a proper solution
@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");
}
});
}
Solution
After playing around with spring security & spring boot I was able to find the root cause and fix it, just enable the CORS at the main class file(Global CORS configuration) and will fix the above issue.
ps: even enabling CORS at its method level was not recognized properly, need to add it in the main class
@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;
}
Answered By - ncgamer99