0

I have the following Configuration Class that implements the WebMvcConfigurer Interface and Overrides the addCorsMappings method. (as described here: https://www.baeldung.com/spring-cors)

@Configuration
//@EnableWebMvc <- I tried with and without, no effect
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

I also have a Configuration Class extending the WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customService = new CustomUserDetailsService();


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http            
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/user/signup*").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/auth*").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/nummern/**").permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/information/").hasRole("OWNER")
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .addFilter(new JwtAuthenticationFilter(authenticationManager()))
            .addFilter(new JwtAuthorizationFilter(authenticationManager()))
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

Whenever I make an HTTP request to my authorization endpoint, using Ajax, I get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/auth?username=Example&password=Example' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Since this approach had no effect, I also tried the approach found in the Spring Security 5 documentation, but that also did not work:

https://docs.spring.io/spring-security/site/docs/5.0.5.RELEASE/reference/htmlsingle/#cors

I am not sure if this is due to my CORS configuration or some CSRF configuration (as far as I am concerned CSRF should be disabled due to my HttpSecurity config):

2020-05-29 13:52:40.377 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /auth?username=Example&password=Example at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-05-29 13:52:40.378 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /auth?username=Example&password=Example at position 4 of 15 in additional filter chain; firing Filter: 'CsrfFilter'
2020-05-29 13:52:40.381 DEBUG 21056 --- [nio-8080-exec-1] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8080/auth?username=Example&password=Example
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@4ea0d6af
2020-05-29 13:52:40.382 DEBUG 21056 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.

I have tried various other suggested solutions and CORS configurations for older Spring Security versions but none of them has had any effect on my issue so far.

This seems like the most recent Solution for a similar question, also didn't work for me:

Spring Boot Security No 'Access-Control-Allow-Origin' header is present on the requested resource Error

EDIT: I tried using a CORS disabling extension for Firefox (and various HTTP clients), but I was not able to see any differences apart from being redirected to the /login endpoint, which I also tried to disable using:

  http.httpBasic().disable()

My Spring Application still throws the same error as mentioned above in all of the test cases.

EDIT #2: I also tried:

    @Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:3000");
        }
    };
}
Oblivial
  • 53
  • 5

2 Answers2

0

I think it doesn't work because you didn't add your origin(localhost:3000) to allowed origins. So Spring doesn't know which origins have access.

Spring guide shows how to do that :

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
        }
    };
}

Also you can use second option specified here

Xnart
  • 101
  • 1
  • 5
0

Apparently the Application was using the default configuration the entire time, which caused none of my Security Configurations to have any effect and hence the CSRF/Cors issues.

The cause was a falsely placed @ComponentScan annotation in my Application class.

With Component Scan:

2020-06-08 11:28:20.764 DEBUG 5612 --- [           main] s.s.c.a.w.c.WebSecurityConfigurerAdapter : Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).
2020-06-08 11:28:20.787 DEBUG 5612 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'authenticated', for any request
2020-06-08 11:28:20.790 DEBUG 5612 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : Validated configuration attributes
2020-06-08 11:28:20.791 DEBUG 5612 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : Validated configuration attributes

Without:

2020-06-08 11:34:56.343 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/user/signup*']
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/auth*']
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'permitAll', for Ant [pattern='/nummern/**']
2020-06-08 11:34:56.344 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'hasRole('ROLE_OWNER')', for Ant [pattern='/information/']
2020-06-08 11:34:56.345 DEBUG 8504 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'authenticated', for any request
Oblivial
  • 53
  • 5