Access-Control-Allow-Origin alwasy set to * in spring boot

46 Views Asked by At

I am setting CORS using the following configurations, in spring boot, but the browser shows as if I am using * not the specified URL !

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("http://localhost:4200"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD",
                "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Origin"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
2

There are 2 best solutions below

2
Anthony Nguyen On
  1. The easier way support by spring boot is sets @CrossOrigin annotation on the controller.

Example:

@CrossOrigin("http://localhost:4200")

  1. Of if you use spring security:
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

And many ways to set cors, follow this article: https://www.baeldung.com/spring-cors

  1. For global configuration:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") 
        .allowedOrigins("http://localhost:4200");
    }
}
0
user3586286 On

After deploying the war on tomcat, It didn't show the *.

so maybe it is only when start from intellij