I know there are many posts about this, but they all seem to be broken or old, in fact none of them fit spring security 6.2.3, spring-boot 3.2.4
I’ve tried various options to allow my frontend to communicate with an endpoint in spring while avoiding the cors problem. Here I bring you one of the solutions I tried but still didn’t work. The endpoint is /api/v1/test
A custom cors configurations class (I want to allow all origins request):
@Component
public class CustomCorsConfiguration implements CorsConfigurationSource {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("*"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("*"));
return config;
}
}
A segurity configuration class:
@Autowired
CustomCorsConfiguration customCorsConfiguration;
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.cors(c -> c.configurationSource(customCorsConfiguration))
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers(
AntPathRequestMatcher.antMatcher("/api/v1/test")
)
.permitAll()
.requestMatchers("/api/**")
.authenticated()
)
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
}
A trivial endpoint to test:
@RestController
@CrossOrigin
@RequestMapping(value = "/api/v1/")
@Slf4j
public class TestController {
@GetMapping(value = "test", produces = "application/json")
@Operation(method = "GET")
public ResponseEntity<Test> getTest() {
...
Why do I keep getting this error from my Angular frontend?
Access to XMLHttpRequest at ‘https://servername/api/v1/test’ from
origin ‘http://localhost:5123’ 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.