0

I have the following configurations:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class SecurityConfig {
  private final JwtAuthFilter jwtAuthFilter;
  private final AuthenticationProvider authenticationProvider;
  private static final String[] PUBLIC_MATCHERS = {"/v1/auth/**"};

  @Bean
  public SecurityFilterChain configure(HttpSecurity http) throws Exception {
    http.csrf()
        .disable()
        .authorizeHttpRequests()
        .requestMatchers(PUBLIC_MATCHERS)
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authenticationProvider(authenticationProvider)
        .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
  }
}
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "TRACE", "CONNECT");
    }
}

And the endpoint:

@RestController
@RequestMapping("/v1/clients")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ClientRestController {
  private final ClientService service;
  private final ClientMapper mapper;

@GetMapping
  public ResponseEntity<Page<ClientResponse>> getByUser(
      @RequestParam(defaultValue = "0") final int page) {
    final var clients = service.findAllByUserLogged(PageRequest.of(page, 10));
    return ResponseEntity.ok().body(clients.map(mapper::toResponse));
  }

But when I send the requests from angular application I get the this:

Access to XMLHttpRequest at 'http://localhost:8080/v1/clients' 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'm sending the Authorization header, in the get, but my application are not sending the header in options request, I don't if it is that is causing this problem. I get error in the two requests.

enter image description here enter image description here

I tried a request right after receiving a 200 from my authenticate endpoint.

rafu
  • 35
  • 1
  • 3
  • 1
    CORS is the MOST asked question when it comes to the spring security tag, it gets asked 5 times a week. there are 100s of questions that handles this also there is an entire chapter in the spring security documentation about CORS https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html#page-title https://stackoverflow.com/questions/36968963/how-to-configure-cors-in-a-spring-boot-spring-security-application downvoted becuase extremly bad research – Toerktumlare Feb 06 '23 at 00:17
  • also no debug logs posted, why are you using the WebMvcConfigurer, are you using MVC in your app? Have you checked in the debug logs that your configuration actually is loaded? have you debugged your application to see that your addCorsMapping function is run on startup? – Toerktumlare Feb 06 '23 at 00:19
  • 2
    @Toerktumlare it is a very common question in Spring Security, but it seems like Spring Security 6 has a tendency to misbehave with regards to custom CORS configurations. rafu: in the SecurityConfig, you can also do the following: ``` .cors(cors -> cors.configurationSource(yourCustomCorsConfigurationSource)); ``` to make sure it will pick up the config you want and not ignore it. – ArthurT Mar 29 '23 at 09:36
  • `Spring Security 6 has a tendency to misbehave with regards to custom CORS configurations` whats your source? most questions i have to answer when it comes to CORS people 1. dont actually understand what CORS is, 2. Havn't read their own logs, 3. Not read the spring security documentation on CORS, but only done some simple googling. 4. read the MVC way of configuring cors, and not the Spring Security way of configuring CORS. My point is, its not spring 6 that is the problem, usually the developer. Because lack of info about CORS is not the problem. – Toerktumlare Mar 29 '23 at 09:42

1 Answers1

-1

Add http.cors() to your filterchain

 http.cors().and().csrf().disable();

Then you can put this in your controller class. But seeing as you already have CorsConfiguration class, you might not need the below. Although the snippet below is a shorter way of doing it.

@CrossOrigin(origins = "http://localhost:4200")
Luigi Woodhouse
  • 332
  • 3
  • 14