0

I added Spring Security (4.2.2) to my Spring Boot (1.5.3) project and implemented a token authentication that works fine.

Then I tried to add CORS. When I now call the API the preflight OPTIONS request returns 400, but the following GET request returns 401. If I disable Spring Security CORS works fine. So, I assume there is something not ideal with regard to the filter ordering.

I added the CORS configuration to the SecurityConfiguration as described here https://github.com/spring-projects/spring-boot/issues/5834#issuecomment-296370088:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private UserDetailsService apiUserDetailsService;

    @Autowired
    private SecurityService securityService;

    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(this.apiUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
        return new AuthenticationTokenFilter();
    }

    @Bean
    public SecurityService securityService() {
        return this.securityService;
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @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;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.debug(true);
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors();

        httpSecurity
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(this.unauthorizedHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/orchestrator/feedback/authenticate/**").permitAll()
                .requestMatchers(new RegexRequestMatcher("/orchestrator/feedback/\\w{2}/applications/\\d+/?", "GET", true)).permitAll()
                .requestMatchers(new RegexRequestMatcher("/orchestrator/feedback/\\w{2}/applications/?", "GET", true)).permitAll()
                .anyRequest().authenticated();

        httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    }
}

And I have a web config like this:

@Configuration  
public class WebConfig extends WebMvcConfigurerAdapter {

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

I already tried a custom filter or FilterRegistrationBean, nothing helps yet. Is something wrong with the httpSecurity builder part or do I have another mistake?

Spring Security Logs:

2017-05-30 13:11:55.939  INFO 36146 --- [io-8081-exec-10] Spring Security Debugger                 : 

************************************************************

Request received for OPTIONS '/orchestrator/feedback/de/applications/1?_=1496142715197':

org.apache.catalina.connector.RequestFacade@4699afc5

servletPath:/orchestrator/feedback/de/applications/1
pathInfo:null
headers: 
host: localhost:8081
connection: keep-alive
pragma: no-cache
cache-control: no-cache
access-control-request-method: GET
origin: http://localhost
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
access-control-request-headers: content-type
accept: */*
referer: http://localhost/
accept-encoding: gzip, deflate, sdch, br
accept-language: en-GB,en;q=0.8,en-US;q=0.6,de;q=0.4,fr;q=0.2,it;q=0.2,es;q=0.2,pt;q=0.2


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CorsFilter
  LogoutFilter
  AuthenticationTokenFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


2017-05-30 13:11:56.073  INFO 36146 --- [nio-8081-exec-1] Spring Security Debugger                 : 

************************************************************

Request received for GET '/orchestrator/feedback/de/applications/1?_=1496142715197':

org.apache.catalina.connector.RequestFacade@4699afc5

servletPath:/orchestrator/feedback/de/applications/1
pathInfo:null
headers: 
host: localhost:8081
connection: keep-alive
pragma: no-cache
cache-control: no-cache
accept: application/json, text/javascript, */*; q=0.01
origin: http://localhost
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
content-type: application/json; charset=utf-8;
referer: http://localhost/
accept-encoding: gzip, deflate, sdch, br
accept-language: en-GB,en;q=0.8,en-US;q=0.6,de;q=0.4,fr;q=0.2,it;q=0.2,es;q=0.2,pt;q=0.2


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CorsFilter
  LogoutFilter
  AuthenticationTokenFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


2017-05-30 13:11:56.075  INFO 36146 --- [nio-8081-exec-1] Spring Security Debugger                 : 

************************************************************

Request received for GET '/error?_=1496142715197':

org.apache.catalina.core.ApplicationHttpRequest@7a954096

servletPath:/error
pathInfo:null
headers: 
host: localhost:8081
connection: keep-alive
pragma: no-cache
cache-control: no-cache
accept: application/json, text/javascript, */*; q=0.01
origin: http://localhost
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
content-type: application/json; charset=utf-8;
referer: http://localhost/
accept-encoding: gzip, deflate, sdch, br
accept-language: en-GB,en;q=0.8,en-US;q=0.6,de;q=0.4,fr;q=0.2,it;q=0.2,es;q=0.2,pt;q=0.2


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  CorsFilter
  LogoutFilter
  AuthenticationTokenFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


2017-05-30 13:11:56.075 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2017-05-30 13:11:56.076 DEBUG 36146 --- [nio-8081-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2017-05-30 13:11:56.076 DEBUG 36146 --- [nio-8081-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2017-05-30 13:11:56.076 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/error] is: -1
2017-05-30 13:11:56.076 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.cors.DefaultCorsProcessor        : Skip CORS processing: response already contains "Access-Control-Allow-Origin" header
2017-05-30 13:11:56.077 DEBUG 36146 --- [nio-8081-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Written [{timestamp=Tue May 30 13:11:56 CEST 2017, status=401, error=Unauthorized, message=Access Denied, path=/orchestrator/feedback/de/applications/1}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@32efecf2]
2017-05-30 13:11:56.077 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-05-30 13:11:56.078 DEBUG 36146 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Successfully completed request
rsdev
  • 161
  • 1
  • 2
  • 9
  • Could you please add Spring Security logs (with level `DEBUG` enabled in your logging configuration) to your question? – dur May 30 '17 at 08:48
  • That's the wrong log. You have to change the log configuration, not the Spring Boot configuration. – dur May 30 '17 at 11:30

3 Answers3

1

Add @CrossOrigin to your controller and it will allow CORS

Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106
0

Security filter ordering changed in Spring Boot 1.5.3. According to this and this, you may try to change spring security filter order by using @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) on your WebSecurityConfigurerAdapter

Ihor Rybak
  • 3,091
  • 2
  • 25
  • 32
0

I finally could solve it by adding the following line to the security configuration:

            .requestMatchers(new RegexRequestMatcher("/orchestrator/feedback/\\w{2}/applications/\\d+/?\\?_=\\d+", "GET", true)).permitAll()

This ensures that the GET request to e.g. ...applications/1?_=1496393166113 is permitted. This url was not captured before.

So, it was a configuration mistake from my side.

rsdev
  • 161
  • 1
  • 2
  • 9