Home > OS >  SpringBoot Security and CORS configured with WebMvcConfigurer fails without calling checkOrigin
SpringBoot Security and CORS configured with WebMvcConfigurer fails without calling checkOrigin

Time:02-24

I am trying to allow some/all origins for global CORS configurations.

Project that I'm working on is using spring security with JWT.

This is my WebSecurityConfig class:

@Configuration
@RequiredArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   /* Removed some of the code for making the question shorter.*/

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
    }

Also following some guides on the internet I've implemented the WebMvcConfigurer interface.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
                .allowedOrigins("http://localhost:8080","http://127.0.0.1:8080")
                .allowedHeaders("Authorization", "Cache-Control", "Content-Type", "Accept", "X-Requested-With",
                        "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin")
                .exposedHeaders("Access-Control-Expose-Headers", "Authorization", "Cache-Control",
                        "Content-Type", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin");
    }
}

My backend application runs on localhost:8443(SSL) and my vue.js(NO SSL) frontend listens on localhost:8080 but whenever I try to make a request in the frontend,

I get this error on firefox: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://127.0.0.1:8443/login. (Reason: CORS request did not succeed). Status code: (null)

I've also tried to add these properties to my application.properties but they didn't make any difference.

management.endpoints.web.cors.allowed-origins=http://localhost:8080
management.endpoints.web.cors.allowed-methods=GET,POST,PUT,DELETE,HEAD

To be able to debug and see what's missing I've placed a break-point to the first line of checkOrigin method in org.springframework.web.cors.CorsConfiguration and I've noticed it is not getting called. Yet, some of the other methods in the same class like addMapping(String pathPattern) and setAllowedOrigins(@Nullable List<String> origins) are getting called by my WebMvcConfigurer implementation.

Also I've noticed some people are using @EnableWebSecurity on their WebConfig class. Which I've also tried and didn't notice any difference in behavior.

These are the dependencies I'm using.

    implementation 'org.springframework.boot:spring-boot-starter-security:2.5.5'
    implementation 'org.springframework.boot:spring-boot-starter-web:2.5.5'
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb:2.5.5'
    implementation 'org.springframework.boot:spring-boot-starter-validation:2.5.5'
    implementation 'org.springframework.boot:spring-boot-starter-websocket:2.5.5'
    implementation 'org.springframework.boot:spring-boot-starter-mail:2.5.5'
    implementation 'io.jsonwebtoken:jjwt:0.9.1'
    implementation 'org.mapstruct:mapstruct:1.4.2.Final'
    implementation 'org.projectlombok:lombok:1.18.22'
    implementation 'org.mapstruct:mapstruct-processor:1.4.2.Final'
    implementation 'org.apache.commons:commons-lang3:3.12.0'
    implementation group: 'commons-io', name: 'commons-io', version: '2.11.0'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'

CodePudding user response:

I don't see any mistake except your WebSecurityConfig class doesn't have an annotation EnableWebSecurity.

You can also check the below answer to enable core without web security.

https://stackoverflow.com/a/41000211/7435950

CodePudding user response:

Okay, I've found the root cause of this issue and wanted to share it.

It was because I'm using a self generated SSL certificate at my backend. I don't know why but when the requested host has an invalid SSL certificate Firefox logs a CORS error. Which was misleading for me. Only when I tried it with chromium, noticed it was talking about SSL by logging et::ERR_SSL_PROTOCOL_ERROR.

After noticing this, all i needed to do is to visit that endpoint directly in a new tab and accept the risks in order to allow it to connect. By doing this in both Chromium and Firefox solved the issue for me which means all my cors requests was hang on my debug point at checkOrigin method.

  • Related