Issue
I have seen a ton of other questions on StackOverflow on this topic, but no solution fixed my problem.
I have a rest API developed with SpringBoot on port 8000
on localhost
. I'm trying to make a request to an endpoint from the browser's fetch
API. I have also enabled CORS with the following bean:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowedHeaders("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.allowedHeaders("*");
}
};
}
Here's my security configuration:
@EnableWebSecurity
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired private UserService userService;
public SecurityConfiguration() {
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/register", "/h2-console/**").permitAll()
.antMatchers("/**").authenticated()
.and().httpBasic();
http.headers().frameOptions().sameOrigin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Instead of all this setup, I still get the following error:
Preflight response is not successful
Fetch API cannot load http://localhost:8000/api/register/ due to access control checks.
Failed to load resource: Preflight response is not successful
Solution
Check https://www.baeldung.com/spring-security-cors-preflight
When using spring security, all requests without a valid auth token are blocked unless mentioned explicitly. The browser is sending a request with options
method. That request will be blocked as per my configuration. So, to exclude cors
from security, we need to enable it.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
...//
}
Answered By - Karthik Chennupati