I was wondering if someone can help me about a problem between Angular2 and Spring Security. Let me explain my issue the best I can.
I do a form (for the example, a very simple form) in Angular2, and with my Login service, I send it in my security page. In my localhost:4200 (angular) I send the username and password that I have juste enter to the localhost:8080/login (spring security) by POST.
The issue is, when I do this, i got this :
XMLHttpRequest cannot load http://localhost:8080/login. Redirect from 'http://localhost:8080/login' to 'http://localhost:8080/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
however, it's because the localhost:8080/login make a redirection, and after this one, the CORS policy comes back even if I allow it everywhere in my Spring code.
The most ankward in it, if I enter the bad credential (like username:"user" but password: "pasodqki") I got this :
XMLHttpRequest cannot load http://localhost:8080/login. Redirect from 'http://localhost:8080/login' to 'http://localhost:8080/login?error' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
And when I did it right, I got the first error and we can see one redirect to localhost:8080 and the other to localhost:8080/login?error, I don't know if it means something.
All my code is here : MyProjectGithub. If anyone have an idea, please help me because I don't understand how we can make this link between Angular and Spring security and I don't find a lot of help on the internet, or I don't understand maybe...
My config :
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors();
http.authorizeRequests()
.antMatchers("/*").hasRole("USER")
.and()
.formLogin();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return source;
}
Like this it works!