使用 WebSecurity.ignoring() 时如何修复 CORS

Mil*_*osc 7 java spring spring-security jwt spring-boot

我正在通过 JWT 授权使用 Spring 构建一个平台。在网关服务中,我有用于解析令牌的自定义过滤器(基于 BasicAuthenticationFilter),但应该仅针对安全配置中标记的路由调用它,以便将.authenticated()任何人都可以访问的路由添加到WebSecurity.ignoring().

问题是添加路径以WebSecurity.ignoring()同时禁用 CORS 配置,并且OPTIONS请求不会返回Access-Control-*标头。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            // Auth service
            .antMatchers("/auth/login", "/auth/renew")
                .permitAll()
            .antMatchers("/auth/logout", "/auth/session/**")
                .authenticated()

            // User service
            .antMatchers(HttpMethod.POST, "/user/")
                .permitAll()
            .antMatchers( "/user/confirm/**", "/user/recover", "/user/validate/**")
                .permitAll()
            .antMatchers("/user/", "/user/change/**")
                .authenticated()

            // further part of routes...

    http
            .formLogin()
                .disable()
            .logout()
                .disable();

    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http.addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtKey));

    http.csrf().disable();

    http.cors();
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            // Auth service
            .antMatchers("/auth/login", "/auth/renew")

            // User service
            .antMatchers(HttpMethod.POST, "/user/")
            .antMatchers( "/user/confirm/**", "/user/recover", "/user/validate/**")

            // further part of routes...
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(corsOrigins);
    configuration.setAllowedMethods(Collections.singletonList("*"));
    configuration.setAllowedHeaders(Collections.singletonList("*"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法只绕过某些路径的特定过滤器?

-解决了-

我通过启用WebMvc和添加 cors 配置解决了我的问题(之前的配置可能会被删除)。

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("http://localhost:3000")
            .allowedMethods("*")
            .allowedHeaders("*")
            .allowCredentials(true)
            .maxAge(3600);
}
Run Code Online (Sandbox Code Playgroud)