javaspringspring-mvccorscross-origin-resource-policy

I get the CORS error while testing my api, I already set the crossorigin configuration but it's not working, Java Spring, Authentication JWT


I created a web application with java spring, I'm using JWT as authentication mechanism, I always get the cors problem even after adding the configuration to allow cross origins, how could I fix it? I'm using spring 6, and spring boot 3 I will provide some of the code, the informations provided are not enough, you could see the whole code on my github repo: Github The problem only happens when I call endpoints that requires authentication, I think there is a problem with the request or the response sent by the server, or maybe the header of the request, it would be better if any of you have the solution to provide me an example of the request I should send using "axios or fetch" Here is my authentication filter :

public class securityConfigurationFilter {

    private final jwtAuthenticationFIlter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;
    private final LogoutHandler logoutHandler;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity)throws Exception{

        httpSecurity
                .csrf()
                .disable()
                .authorizeHttpRequests()
                .requestMatchers(
                        "/api/v1/account/register",
                        "/api/v1/account/password-recovery/*/*",
                        "/api/v1/account/authenticate",
                        "/api/v1/account/emailValidation/*",
                        "/api/v1/questions",
                        "/swagger-ui/index.html#",
                        "/v2/api-docs",
                        "/v3/api-docs",
                        "/v3/api-docs/**",
                        "/swagger-ressources",
                        "/swagger-ressources/**",
                        "/configuration/ui",
                        "/configuration/security",
                        "/swagger-ui/**",
                        "/webjars/**",
                        "/swagger-ui.html"
                )
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)



                .logout()
                .logoutUrl("/api/v1/account/logout")
                .addLogoutHandler(logoutHandler)
                .logoutSuccessHandler(
                        (request,
                         response,
                         authentication) ->
                        SecurityContextHolder.clearContext());
  return httpSecurity.build();
    }

And here is the webConfiguration :

@Configuration
public class webConfigCors implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry coreRegistry) {
        coreRegistry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*");
    }
}

I tried to add the crossorigin annotation for each endpoint, I also tried to change the webcross configuration to accept credentiels like this :

@Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://127.0.0.1:5500"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

, And by the way I want it to be accessible by all the origins not only my local host as fixed in the configuration above


Solution

  • I think I found the solution, if you have the same problem with the same configuration in securityFilter bean, you should add the following line right after .disable() in the configuration, you will have something like this :

     @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity)throws Exception{
    
        httpSecurity
                .csrf()
                .disable()
                .cors()  // this is how to disable cors 
                .authorizeHttpRequests()
    

    .... the rest of the configuration