You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot登录路由全局CORS配置失效问题求助

问题分析与解决方案

你遇到的核心问题是:自定义的/api/signup路由能正常通过CORS校验,但修改路径后的Spring Security登录接口/api/login出现跨域错误,原因在于Spring Security过滤器链的执行优先级高于Spring MVC的CORS配置。当/api/login请求到达时,Security的过滤器先处理请求,但此时并未携带CORS响应头,导致浏览器拦截。

下面是具体修复步骤:


1. 调整全局CORS配置类

移除AppConfig上的@EnableWebSecurity注解(该注解已在SecurityConfig中声明,重复标注会导致配置冲突),并完善CORS规则:

@Configuration
public class AppConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true); // 允许携带凭证(如Cookie)
    }
}

2. 在Security配置中启用CORS支持

在SecurityConfig中添加CORS配置,让Security过滤器链处理请求时自动注入CORS响应头:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final UserDetailsService userDetailsService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    public SecurityConfig(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(authenticationManager());
        customAuthenticationFilter.setFilterProcessesUrl("/api/login");
        
        http.csrf().disable()
            .cors() // 启用Security层面的CORS支持
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
                .antMatchers("/api/login", "/api/refreshtoken", "/api/signup").permitAll()
                .antMatchers(HttpMethod.GET, "/api/userprofile").hasAuthority("USER")
                .anyRequest().authenticated();
        
        http.addFilter(customAuthenticationFilter);
        http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    // 定义Security使用的CORS配置源,与MVC配置保持一致
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowCredentials(true);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/api/**", configuration);
        return source;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}

修复原理

  • Spring Security的过滤器链在Spring MVC的DispatcherServlet之前执行,因此/api/login请求会先经过Security处理,此时如果没有配置Security层面的CORS,就不会添加Access-Control-Allow-Origin等响应头。
  • 通过http.cors()启用Security的CORS支持,并绑定自定义的CorsConfigurationSource,确保Security在处理请求时自动注入正确的CORS头,解决跨域拦截问题。

内容的提问来源于stack exchange,提问作者g-mahendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:45:50