Search code examples
javaspringwebsecurity

Configuring cors in spring boot application. Bean CorsConfigurationSource doesnt work


So i cant configure cors. My angular app cant send api request because of error. I can do requests by soapUI and they are working fine. But from browser there is:

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

I was looking for answers and they look like my class.

Im using spring boot web security.

@EnableWebSecurity
@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {

    @Value(value = "${auth0.apiAudience}")
    private String apiAudience;
    @Value(value = "${auth0.issuer}")
    private String issuer;


    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowCredentials(true);
        configuration.addAllowedHeader("Authorization");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JwtWebSecurityConfigurer
                .forRS256(apiAudience, issuer)
                .configure(http)
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,"/api/public").permitAll()
                .antMatchers(HttpMethod.GET, "/api/private").authenticated()
                .antMatchers(HttpMethod.GET, "/api/private-scoped").hasAnyAuthority("read:posts");
    }
}

This bean should add this cors header but it doesnt. Maybe you know any better idea of doing this? What is difference beetwen WebSecurityConfigurerAdapter and WebMvcConfigurerAdapter?


Solution

  • According to this you should add .cors().and() in your configure() method as well.

    There are also other possible solutions, for example by setting the CORS-configuration specific to each endpoint as seen here.

    If you want to enable CORS for your whole application though, the first way is much prettier.

    The difference between WebSecurityConfigurerAdapter and WebMvcConfigurerAdapter is, that WebSecurityConfigurerAdapter is used to configure anything related to the security of your webapp, like authentication and authorization. With the WebMvcConfigurerAdapter you can customize the Java-based configuration for Spring MVC.