Issue
I have a react based frontend and a spring backend (which uses spring security). I have disabled CORS in the spring security configuration (at least I think so) but the requests still gives this error:
Access to XMLHttpRequest at 'http://localhost:8080/api/v1/registration/' from origin 'http://localhost:3000' 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.
This is the frontend:
const register = () => {
//var url = process.env.REACT_APP_SERVER_IP + "/api/v1/registration";
var url = "http://localhost:8080/api/v1/registration/";
var userData = {
email: "[email protected]",
username: "uname",
password: "pass"
}
axios.post("http://localhost:8080/api/v1/registration/", userData
).then(function (response) {
alert(response);
}).catch(function (error) {
alert(error);
});
}
This is the backend:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/api/v*/registration/**")
.permitAll()
.anyRequest()
.authenticated().and()
.formLogin();
}
Any idea as to why requests are still blocked?
Solution
I solved the problem by adding in the react application as an exception. The security settings are as follows:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
http.csrf().disable();
// Authorize all requests.
http.authorizeRequests()
.antMatchers("/api/v*/registration/**")
.permitAll()
.anyRequest()
.authenticated().and()
.formLogin();
}
The react application was set as an exeption using this bean within the security config.
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList(corsConfig.getAddress()));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
configuration.setExposedHeaders(Arrays.asList("Authorization", "content-type"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
Here the corsConfig.getAddress() gets the address of the react application from a config I setup, for example http://localhost:3000. Also note that in the code csrf is disabled, which as others have noted isn't a great idea.
Answered By - Ivaldir