Home > OS >  Spring Security CORS Blocked By Policy
Spring Security CORS Blocked By Policy

Time:01-20

This should be easy, but of course since it's Spring Security, it's not.

I am attempting to access a relatively simple api running as a Spring Boot application from an Angular application. Angular makes the calls to the API just fine, but the backend blocks the request due to CORS policy:

I added the following to my Security configuration:

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://localtest.me:4200","http://localtest.me:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    @Profile("dev")
    public SecurityFilterChain devFilterChain(HttpSecurity http) throws Exception {
        
        // define a custom filter, irrelevant to question
        
        // @formatter:off
        http
            .addFilterAfter(filter, ConcurrentSessionFilter.class)
            .authorizeRequests()
                .antMatchers("/path1","/path2","/logout").permitAll()
                .anyRequest().authenticated()
            .and()
            .cors();

        // @formatter:on
        return http.build();
        
    }

This STILL does not prevent the CORS policy block.

I've also tried putting various iterations of @CrossOrigin (with and without origins argument):

  • on the Controller class
  • on the endpoint method itself

Am I making a simple error causing this?

Edit: I added breakpoints to Spring's CorsFilter, and they are not being hit.

Edit: Adding screenshot by request:

enter image description here

enter image description here

CodePudding user response:

try to add this at the head ( beggining of your controller)

@CrossOrigin(origins = "http://localhost:{youy_angular_application_port}")
public class YourRestController {
}

CodePudding user response:

Not the proudest and most beautiful solution, but some months ago, I also needed to expose some endpoints to my frontend, so my angular application could send requests to them.

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/user").allowedOrigins("http://localhost:4200");
                registry.addMapping("/post").allowedOrigins("http://localhost:4200");
                registry.addMapping("/post/").allowedOrigins("http://localhost:4200");
                registry.addMapping("/user/{id}").allowedOrigins("http://localhost:4200");
                registry.addMapping("/post/{id}").allowedOrigins("http://localhost:4200");
                registry.addMapping("/post/user").allowedOrigins("http://localhost:4200");
                registry.addMapping("/post/user/").allowedOrigins("http://localhost:4200");
                registry.addMapping("/post/user/{id}").allowedOrigins("http://localhost:4200");
                registry.addMapping("/user/").allowedOrigins("http://localhost:4200");
            }
        };
    }

The bean can get implemented where ever, since its a bean. In my case I implemented it in the MainApplication.java class.

  • Related