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

Hey everyone, I’m having trouble with CORS when trying to send API requests from my frontend to my backend. I’m using Spring Boot with Spring Security.

Every time I try to make a request, I get this error in my console:

Access to XMLHttpRequest at 'http://localhost:8080/login' from 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’ve tried adding @CrossOrigin(origins = "http://localhost:4200") to my controller, but it’s not working. Here’s what my controller looks like:

@RestController
@AllArgsConstructor
@CrossOrigin(origins = "http://localhost:4200")
public class UserAuthController {
    private final AccountService accountService;
    
    @PostMapping("/signup")
    public ResponseEntity<String> signup(@RequestParam String username,
                                         @RequestParam String email,
                                         @RequestParam String password) {
        try {
            this.accountService.createAccount(username, email, password);
            return ResponseEntity.ok("Account created successfully");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}

And here’s my security config:

public class WebSecuritySetup {
    @Bean
    public SecurityFilterChain filterChainConfig(HttpSecurity http) throws Exception {
        http
            .cors(Customizer.withDefaults())
            .csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests((requests) -> requests
                .anyRequest().permitAll()
            );
        return http.build();
    }
}

Any ideas on what I’m doing wrong or how to fix this CORS issue? Thanks in advance!

I’ve encountered similar CORS issues in my Spring Boot projects. While @CrossOrigin can work, I’ve found a more robust solution is to configure CORS globally. Try adding a CorsConfigurationSource bean to your WebSecuritySetup class:

@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(“*”));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration(“/**”, configuration);
return source;
}

Then, in your filterChainConfig method, replace .cors(Customizer.withDefaults()) with .cors(cors → cors.configurationSource(corsConfigurationSource())). This approach has consistently resolved CORS issues for me across various Spring Boot applications.

have u considered using a proxy server? it can be a lifesaver for CORS probs! i use nginx as a reverse proxy, and it handles CORS headers seamlessly. Plus, it’s great for local dev. what do u think about trying that approach? might be easier than tweaking spring configs!

hey, had similar issues. try adding this to ur application.properties:

spring.web.cors.allowed-origins=http://localhost:4200
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS

it worked 4 me without messing with the security config. hope this helps!