Frontend to backend API calls blocked by CORS - how to fix?

Hey everyone, I’m running into a frustrating issue with my web app. I’m trying to send API requests from my frontend (running on localhost:4200) to my backend (on localhost:8080), but I keep getting CORS errors in the console.

The error message says something about the ‘Access-Control-Allow-Origin’ header missing. I’ve tried adding @CrossOrigin to my Spring Boot controller, but it’s not working.

Here’s a simplified version of my controller:

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class UserController {
    @PostMapping("/signup")
    public ResponseEntity<String> createAccount(@RequestParam String name,
                                                @RequestParam String mail,
                                                @RequestParam String pass) {
        // Account creation logic here
        return ResponseEntity.ok("Account created");
    }
}

And here’s my basic security config:

@Configuration
public class WebSecuritySetup {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
                .anyRequest().permitAll();
        return http.build();
    }
}

Any ideas on what I’m missing or doing wrong? Thanks in advance!

I’ve encountered this issue before, and it can be quite frustrating. While the @CrossOrigin annotation is a good start, it’s not always sufficient, especially with more complex security configurations. Have you considered implementing a global CORS configuration? This approach tends to be more robust.

In your WebSecurityConfig class, try adding a corsConfigurationSource() method:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("*"));
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

Then, modify your filterChain method to use this configuration:

http.cors().configurationSource(corsConfigurationSource());

This should provide a more comprehensive CORS setup. Let me know if you still face issues after trying this approach.

hmmm, have u checked ur browser console for any specific error messages? sometimes the exact CORS issue can be found there. also, try using a CORS browser extension to temporarily disable CORS - it can help isolate if its really a server-side problem or smthing else. what kinda frontend framework r u using btw?

hey leo, i had similar issues. try adding a CorsConfiguration bean in ur security config:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    config.setAllowedMethods(Arrays.asList("*"));
    config.setAllowedHeaders(Arrays.asList("*"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}

this worked 4 me. good luck!