【问题标题】:CORS not working for Spring Boot application in combination with Spring SecurityCORS 不适用于结合 Spring Security 的 Spring Boot 应用程序
【发布时间】:2017-10-30 04:26:58
【问题描述】:

我将 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 builder 部分有问题还是我还有另一个错误?

Spring 安全日志:

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

【问题讨论】:

  • 能否将 Spring Security 日志(在日志配置中启用级别 DEBUG)添加到您的问题中?
  • 那是错误的日志。您必须更改日志配置,而不是 Spring Boot 配置。

标签: spring spring-boot spring-security cors


【解决方案1】:

Spring Boot 1.5.3 中更改了安全过滤器顺序。根据thisthis,您可以尝试使用更改弹簧安全过滤器顺序 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 在您的 WebSecurityConfigurerAdapter 上

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2021-05-29
        • 2017-01-31
        • 2016-03-13
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多