无法在 Spring Security 中为 oauth/token 端点启用 CORS

Posted

技术标签:

【中文标题】无法在 Spring Security 中为 oauth/token 端点启用 CORS【英文标题】:Unable to enable CORS for oauth/token endpoint in Spring Security 【发布时间】:2017-09-25 11:26:22 【问题描述】:

我无法在我的 Spring REST API 上启用对 oauth/token 端点的 CORS 支持。

资源服务器配置:

@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter 

    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Autowired
    private CustomLogoutSuccessHandler customLogoutSuccessHandler;

    @Autowired
    private AuthorityService roleService;

    @Bean
    public AccessDecisionManager accessDecisionManager() 
        List<AccessDecisionVoter<? extends Object>> decisionVoters = new ArrayList<>();
        decisionVoters.add(new DynamicAuthorizationVoter(roleService));
        UnanimousBased unanimousBased = new UnanimousBased(decisionVoters); 
        return unanimousBased;
    

    @Bean
    public CorsFilter corsFilter() 
      final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
      final CorsConfiguration corsConfiguration = new CorsConfiguration();
      corsConfiguration.setAllowCredentials(true);
      corsConfiguration.addAllowedOrigin("*");
      corsConfiguration.addAllowedHeader("*");
      corsConfiguration.addAllowedMethod("*");
      urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
      return new CorsFilter(urlBasedCorsConfigurationSource);
    

    @Override
    public void configure(HttpSecurity http) throws Exception 

        http
            .addFilterBefore(corsFilter(), ChannelProcessingFilter.class)
            .authorizeRequests()
                .antMatchers("/admin/user/forgotPassword**").permitAll()
                .antMatchers("/admin/user/resetPassword**").permitAll()
                .antMatchers("/admin/user/changePassword**").authenticated()

                .anyRequest().authenticated()
            .accessDecisionManager(accessDecisionManager())
                .and()
            .exceptionHandling()
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .and()
            .logout()
                .logoutUrl("/oauth/logout")
                .logoutSuccessHandler(customLogoutSuccessHandler)
                .and()
            .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
            .headers()
                .frameOptions().disable()
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    

授权服务器

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware 

    private static final String ENV_OAUTH = "authentication.oauth.";
    private static final String PROP_CLIENTID = "clientid";
    private static final String PROP_SECRET = "secret";
    private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

    private RelaxedPropertyResolver propertyResolver;

    @Autowired
    TokenStore tokenStore;

    @Bean
    public TokenEnhancer tokenEnhancer() 
        return new OAuth2TokenEnhancer();
    

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception 
        endpoints
        .tokenStore(tokenStore)
        .tokenEnhancer(tokenEnhancer())
        .authenticationManager(authenticationManager)
        ;
    

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception 
        clients
        .inMemory()
        .withClient(propertyResolver.getProperty(PROP_CLIENTID))
        .scopes("read", "write")
        .authorizedGrantTypes("password", "refresh_token")
        .secret(propertyResolver.getProperty(PROP_SECRET))
        .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
    

    @Override
    public void setEnvironment(Environment environment) 
        this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
    

安全配置:

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

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() 
        return new BCryptPasswordEncoder();
    

    @Autowired
    private DataSource dataSource;

    @Bean
    public TokenStore tokenStore() 
        return new JdbcTokenStore(dataSource);
    

    @Bean
    public AuthenticationProvider customAuthenticationProvider() 
        CustomAuthenticationProvider impl = new CustomAuthenticationProvider();
        impl.setUserDetailsService(userDetailsService);
        impl.setPasswordEncoder(bCryptPasswordEncoder());
        return impl;
    

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
        auth.authenticationProvider(customAuthenticationProvider());
    

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception 
        return super.authenticationManagerBean();
    

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
    public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration 

        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() 
            return new OAuth2MethodSecurityExpressionHandler();
        

    

我尝试添加自定义过滤器,但飞行前OPTIONS 仍然通过过滤器链。我知道它必须与安全过滤器的顺序有关,但我无法弄清楚究竟是什么在这里不起作用。

以下是处理请求时的日志。

o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/token']
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/oauth/token'
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : matched
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
    2017-04-27 20:03:29.207 DEBUG 20972 --- [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@237e2d31
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', GET]
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'OPTIONS /oauth/token' doesn't match 'GET /logout
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', POST]
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'OPTIONS /oauth/token' doesn't match 'POST /logout
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', PUT]
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'OPTIONS /oauth/token' doesn't match 'PUT /logout
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', DELETE]
    2017-04-27 20:03:29.207 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'OPTIONS /oauth/token' doesn't match 'DELETE /logout
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : /oauth/token?username=admin&password=admin123&grant_type=password at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/oauth/token'; against '/oauth/token'
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /oauth/token?username=admin&password=admin123&grant_type=password; Attributes: [fullyAuthenticated]
    2017-04-27 20:03:29.208 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
    2017-04-27 20:03:29.209 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@2741ad86, returned: -1
    2017-04-27 20:03:29.210 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

    org.springframework.security.access.AccessDeniedException: Access is denied
        at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_111]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_111]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
        at java.lang.Thread.run(Unknown Source) [na:1.8.0_111]

    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using Ant [pattern='/**', GET]
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'OPTIONS /oauth/token' doesn't match 'GET /**
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.s.HttpSessionRequestCache        : Request not saved as configured RequestMatcher did not match
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter     : Calling Authentication entry point.
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@b51f9bf, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : httpRequestMediaTypes=[]
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : Did not match any media types
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using OrRequestMatcher [requestMatchers=[RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest], AndRequestMatcher [requestMatchers=[NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@b51f9bf, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@b51f9bf, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]]]]]
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using AndRequestMatcher [requestMatchers=[NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@b51f9bf, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@b51f9bf, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]]]
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@b51f9bf, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]]
    2017-04-27 20:03:29.211 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : httpRequestMediaTypes=[]
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : Did not match any media types
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.matcher.NegatedRequestMatcher  : matches = true
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@b51f9bf, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : httpRequestMediaTypes=[]
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.u.m.MediaTypeRequestMatcher      : Did not match any media types
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@14842e3
    2017-04-27 20:03:29.212 DEBUG 20972 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

【问题讨论】:

【参考方案1】:

我通过从 configure(HttpSecurity http) Override 方法中删除 .addFilterBefore(corsFilter(), ChannelProcessingFilter.class) 来修复它。

【讨论】:

希望它有意义吗?

以上是关于无法在 Spring Security 中为 oauth/token 端点启用 CORS的主要内容,如果未能解决你的问题,请参考以下文章

Spring:HttpSession在集群Tomcat故障转移中为SPRING_SECURITY_CONTEXT返回了空对象

如何在jsp中为spring security auth异常显示自定义错误消息

如何避免自定义过滤器在spring-security中为不安全的url运行

如何在 Spring Security 中为所有请求添加 jwt 身份验证标头?

如何在spring security中为来自两个不同表的不同用户配置身份验证?

Spring Security 自定义登录回退