1

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.

2 Answers2

3

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

Ekansh Rastogi
  • 2,418
  • 2
  • 14
  • 23
  • 1
    If you're working with Spring-Security, you additionally need to mention `HttpSecurity#cors()` method in the security config. See [this](https://www.baeldung.com/spring-cors#cors-with-spring-security) – Mansur Sep 21 '22 at 07:41
2

In older version of Spring boot we extend WebSecurityConfigurerAdapter in our SecurityConfiguration class but In recent versions of Spring boot , Spring deprecates this approach and encourages a component-based security configuration.

so if you using component-based security configuration. then Inside SecurityConfiguration class, after providing filters to http inside SecurityFilterChain method, use http.cors(); before building http.build();.

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfiguration {

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .csrf()
        ----
        -----
    ;
    http.cors();    //  <- this is what you need to provide

    return http.build();
  }
}

and then in restControllers provide @CrossOrigin(origins = "http://localhost:3000") use your frontend url instead of 3000,

@RequiredArgsConstructor
@RequestMapping("/api/v1/customer")
@RestController
@CrossOrigin(origins = "http://localhost:3000")  // <- use your url of frontend
public class UserController {

    private final UserService userService;

    @GetMapping("/userName")
    public ResponseEntity<String> userName(HttpServletRequest request){
        return ResponseEntity.ok(userService.getUserName(request));
    }
}

happy coding ☺️