Search code examples
javaspring-bootspring-mvcspring-security

How to resolve CORS issue without using Spring Security


I have this WebMvcConfigurer which works totally fine when deployed over the server. But when I try to send a request from my locally served Angular project to the server, I get the following error.

Access to XMLHttpRequest at 'https://sub.domain.com/api/staff/logout' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My Config is as follows:

@Configuration
@EnableWebMvc
public class WebMvcConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedOrigins("*")
                        .allowedHeaders("*")
                        .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                        .allowCredentials(true).maxAge(3600);
            }

            /**
             * To add our interceptor into Spring configuration, we need to override
             * addInterceptors() method WebMvcConfig class that implements WebMvcConfigurer.
             */
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new AppInterceptor());
            }
        };
    }
}

I have referred to other questions my didn't find anything that solved my problem. Thanks in advance.


Solution

  • As I'll be implementing Spring Security in the future, and though the question says without Spring Security, I solved this issue by adding Spring Security to the project,

    The starter dependency:

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
    

    The Configuration Class:

    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.web.cors.CorsConfiguration;
    
    import java.util.List;
    
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowedHeaders(
                    List.of("Authorization", "Cache-Control", "Content-Type", "X-PT-SESSION-ID", "NGSW-BYPASS"));
            corsConfiguration.setAllowedOrigins(List.of("*"));
            corsConfiguration
                    .setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PUT", "OPTIONS", "PATCH", "DELETE"));
            corsConfiguration.setAllowCredentials(true);
            corsConfiguration.setExposedHeaders(List.of("Authorization"));
    
            http.authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated().and().csrf().disable()
                    .cors().configurationSource(request -> corsConfiguration);
    
        }
    }
    

    I referred this answer, and there are other answers that might be helpful to others as well. Do check it out.