CORS不能与Spring Security一起使用Spring Boot应用程序

时间:2017-05-29 20:00:10

标签: spring spring-boot spring-security cors

我将Spring Security(4.2.2)添加到我的Spring Boot(1.5.3)项目中,并实现了令牌认证工作正常。

然后我尝试添加CORS。当我现在调用API时,预检OPTIONS请求返回400,但是以下GET请求返回401.如果我禁用Spring Security CORS工作正常。因此,我认为在滤波器排序方面存在一些不理想的东西。

我将CORS配置添加到SecurityConfiguration,如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);
    }
}

我有一个像这样的网络配置:

@Configuration  
public class WebConfig extends WebMvcConfigurerAdapter {

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

我已经尝试过自定义过滤器或FilterRegistrationBean,但没有任何帮助。 httpSecurity构建器部分有问题还是我有其他错误?

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

3 个答案:

答案 0 :(得分:0)

Spring Boot 1.5.3中更改了安全过滤器顺序。根据{{​​3}}和this,您可以尝试使用更改Spring安全过滤器顺序 WebSecurityConfigurerAdapter上的@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)

答案 1 :(得分:0)

我终于可以通过在安全配置中添加以下行来解决它:

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

这确保了对例如GET的请求。 ...应用程序/ 1?_ = 1496393166113是允许的。此网址之前未被捕获。

所以,这是我身边的配置错误。

答案 2 :(得分:0)

@CrossOrigin添加到您的控制器,它将允许CORS