I am trying to setup CORS on my Java Spring project.
Separately I have an Angular CLI application with a login page, I would like to authenticate a user using my Spring API.
I am getting the error on the client
origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I get this on the server log:
No mapping found for HTTP request with URI [/authenticateUser]
I have tried a number of examples from other threads but the client error doesn't change so I am a bit confused where to configure cors
I have a AppSecurityConfig
class which extends
WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
User.UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser(users.username("user1").password("password").roles("ROLE1"))
.withUser(users.username("user2").password("password").roles("ROLE2"))
.withUser(users.username("user3").password("password").roles("ROLE3"));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/loginPageUrl")
.loginProcessingUrl("/authenticateUser")
.permitAll();
}
My Angular service makes the request:
authenticateUser(json: any) {
return this.http.post('http://localhost:8085/authenticateUser'
, json, {headers : new HttpHeaders()
.set('Authorization', '')
});
}
The json passed in is:
{ username: this.username, password: this.password }
Adding the following method to my AppSecurityConfig class resolved the 'No 'Access-Control-Allow-Origin' header is present on the requested resource' error.
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.addAllowedHeader("content-type");
configuration.addAllowedHeader("Access-Control-Allow-Origin");
configuration.addAllowedHeader("Authorization");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}