I’m encountering a persistent error whenever I attempt to send a request from my frontend to the backend service. I’m building the backend with Spring Boot and utilizing Spring Security for authentication.
Received Error:
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 attempted to resolve this by implementing the @CrossOrigin annotation:
@RestController
@AllArgsConstructor
@CrossOrigin(origins = "http://localhost:4200")
public class AuthController {
private final UserService userService;
@PostMapping("/register")
public ResponseEntity<String> register(@RequestParam String username,
@RequestParam String email,
@RequestParam String password) {
try {
this.userService.registerUser(username, email, password);
return ResponseEntity.ok("User registered successfully");
} catch (Exception e) {
System.err.println(e.getMessage());
return ResponseEntity.badRequest().body(e.getMessage());
}
}
}
And here is how I’ve set up my security configuration:
public class SpringSecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((requests) -> requests
.anyRequest().permitAll()
);
return http.build();
}
}
What could be the missing piece to fix this? Any suggestions would be appreciated.