Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable CORS at Spring Security level in Spring boot [closed]

I am working with a spring boot application which uses Spring Security. I have tried @CrossOrigin to enable cors but it didn't work.

If you want to find my error refer this

Spring Blogs says that when we are working with spring security, we must enable cors at spring security level.

And my project is below.

Can anyone explain where should I put those configuration and how to find the spring security level.

like image 567
Lahiru Gamage Avatar asked Feb 22 '18 11:02

Lahiru Gamage


People also ask

How do I enable CORS spring boot Microservices?

Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

How can the CORS configuration be enabled for controller method?

27.2 Controller method CORS configuration You can add an @CrossOrigin annotation to your @RequestMapping annotated handler method in order to enable CORS on it.


1 Answers

this is a way to make Spring Security 4.1 support CROS with Spring BOOT 1.5

  @Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
           .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

with

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable();
        http.cors();
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
like image 108
becher henchiri Avatar answered Oct 05 '22 14:10

becher henchiri