Why I am getting CORS error though i configured from server side in spring boot and react?

Viewed 124

In my server-side application, I have enabled CORS globally like this.

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "PATCH")
                        .allowedHeaders("*")
                        .allowedOrigins("*");
            }
        };
    }

My client-side application running in react and in useEffect hook,s I'm calling a backend API like this.

useEffect(() => {
    async function fetchData() {
      const dataArray = await axios({
        url: "http://localhost:9001/getAllCompany/7",
        method: "GET",
        headers: { 'Authorization': "Bearer " + authctx.token },
      });

      setCompany(dataArray.data);
      return dataArray;
    }
    fetchData();
  }, [authctx.token]);

Although I have enabled cors the is API calls not working and network call shows like

enter image description here

How can I fix this issue?

2 Answers

There are some situations when we are dealing with spring security. At that point we have to add http.cors(); inside the security configuration class.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http.csrf().disable()
                .authorizeRequests().antMatchers("/user").hasRole("USER")
                .antMatchers("/admin").hasAnyRole("ADMIN")
                .antMatchers("/company/login", "/register","/subscribe/{userId}", "/addDataRequest/{userId}").permitAll().anyRequest().authenticated()
    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
                and().addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }

This works for me.

I guess you have forget to add OPTIONS in the allowedMethods block. This is the reason your pre-flight request from browser is failing and it's not working as expected.

Refer my old answer: https://stackoverflow.com/a/63202865/7200018

Related