首页 > 解决方案 > 使用 WebSecurity.ignoring() 时如何修复 CORS

问题描述

我正在使用 Spring 构建一个平台,并通过 JWT 授权。在网关服务中,我有用于解析令牌的自定义过滤器(基于 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;
}

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

-解决了-

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

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

标签: javaspringspring-bootspring-securityjwt

解决方案


推荐阅读