Skip to content
Advertisement

CORS errors using Spring Boot, Spring Security and React

Good morning.

I have been fighting with this issue for the past two days so I decided to post a question about it.

Basically I have a Spring Boot project which executes basic CRUD operations through a React JS front-end. Everything seemed to work fine until I added Spring Security to the project. Since then whenever I make a request (using axios) from the front-end I get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/calciatore/list' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Before implementing Spring Security everything worked perfectly just using @CrossOrigin(origins = "*") in my back-end controllers, but now I always get that error even if the URL is configured not to be protected through login by Spring Security.

In the meanwhile, I have no problems making any request (POST for login or GET for data fetching) from Postman.

I tried looking for a solution all around the internet but still didn’t find one.

If you need me to show a portion of code just ask.

Thanks in advance.

Advertisement

Answer

Try using the global CORS config as shown in below code to allow CORS for all endpoints.

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {

        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/**")
                        .allowedMethods(CorsConfiguration.ALL)
                        .allowedHeaders(CorsConfiguration.ALL)
                        .allowedOriginPatterns(CorsConfiguration.ALL);
            }
        };
    }
}

Since spring boot 2.4 you are supposed to use allowedOriginPatterns instead of allowedOrigins. Also you cannot use wildcard ‘*’ along with credentials : true

3 People found this is helpful
Advertisement