Spring CorsFilter 似乎无法正常工作,但仍会收到 401 的预检请求

Posted

技术标签:

【中文标题】Spring CorsFilter 似乎无法正常工作,但仍会收到 401 的预检请求【英文标题】:Spring CorsFilter does not seem to work still receiving a 401 on preflight requests 【发布时间】:2016-11-30 19:12:19 【问题描述】:

您好,我是 Spring Security 的新手,正在尝试弄清楚如何配置身份验证服务器以发布令牌。我现在遇到的问题是我在 Cors 预检请求中收到 401 或 403,并且不确定如何解决下面是基于少数教程的准系统实现

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework http://www.baeldung.com/spring-security-oauth-jwt

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
@PropertySource(value = "classpath:oauth.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter 

    @Autowired
    UserRepository userRepository;


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


    @Override
    public void configure(WebSecurity web) throws Exception 

        super.configure(web);
    

    @Autowired
    ObjectMapper mapper;




    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http.csrf().disable();

        http.authorizeRequests().antMatchers(HttpMethod.OPTIONS,"/oauth/token").permitAll()
        .anyRequest().authenticated();
    




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

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception

        auth.inMemoryAuthentication().
        withUser("john").password("123").roles("USER").
        and().
        withUser("tom").password("111").roles("ADMIN");

    
    @Bean
    public FilterRegistrationBean corsFilter() 
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter2());
        bean.setOrder(0);
        return bean;
    





@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter

    @Autowired
    private Environment env;

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


    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer)
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception
        clients.inMemory().withClient("acme").secret("acmesecret").authorizedGrantTypes("authorization_code", "refresh_token",
                  "password").scopes("openId");
    

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
        final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(),accessTokenConverter()));
        endpoints.tokenStore(tokenStore())
                 .tokenEnhancer(tokenEnhancerChain)
                 .authenticationManager(authenticationManager);

    

    @Bean
    public JwtAccessTokenConverter accessTokenConverter()
        final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        return converter;
    

    @Bean
    public TokenStore tokenStore()

        return new JwtTokenStore(accessTokenConverter());

    

    @Bean
    public FilterRegistrationBean corsFilter() 
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter2());
        bean.setOrder(0);
        return bean;
    

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() 
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    

CorsFilter2 是在 spring 4.2 中引入的 spring cors 过滤器,我正在使用它来插入正确的响应标头以发送回客户端。

【问题讨论】:

【参考方案1】:

所以我发现了我的问题,我必须将我的网络安全配置为忽略 CoresRequest 请求,所以在网络安全的配置块中我必须设置这个

    web.ignoring().requestMatchers(CorsUtils::isPreFlightRequest);

它开始起作用了。

【讨论】:

嘿,你在哪里配置的,我得到:'''The method ignoring() is undefined for the type ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry´´´ 如果我在 ´´´authorizeRequests 之后设置它´´´ 和 ´´´ 对于 http 之后的 HttpSecurity´´´´ 直接类型,方法 ignoring() 未定义 @mattobob 我将它添加到我的 SecurityConfig 中的配置方法中,方法签名应该类似于这个 public void configure(WebSecurity web) throws Exception

以上是关于Spring CorsFilter 似乎无法正常工作,但仍会收到 401 的预检请求的主要内容,如果未能解决你的问题,请参考以下文章

使用 CorsFilter 和 spring security 时出现 Cors 错误

休息资源的 Grails spring-security 静态规则似乎无法正常工作

尽管ui-route和provider似乎工作正常,但我无法在angularjs中加载视图......这是一段代码

Spring 跨域问题CORS (Cross Origin Resources Share)

无法使用 Spring Boot 和 Angular 修复 CORS 问题 [重复]

为什么Spring-Data-JPA Async无法正常工作?