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

如何在Spring Security过滤器中配置CORS授权解决/login接口跨域问题

解决方案

你遇到的问题是Spring Security默认没有配置跨域规则,且OPTIONS预检请求没有被放行导致的,按照以下步骤修改即可:

步骤1:在SecurityConfig中添加CORS配置Bean

在SecurityConfig.java类中添加如下Bean:

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

// 类内部添加以下方法
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    // 允许所有来源,生产环境请替换为前端实际域名
    config.addAllowedOriginPattern("*");
    // 允许所有请求头
    config.addAllowedHeader("*");
    // 允许所有请求方法
    config.addAllowedMethod("*");
    // 允许携带凭证(如Cookie、Authorization头)
    config.setAllowCredentials(true);
    // 预检请求缓存时间,单位秒,减少重复预检请求
    config.setMaxAge(3600L);
    
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}

步骤2:修改Security配置放行OPTIONS预检请求

浏览器发送跨域非简单请求前会先发送OPTIONS类型的预检请求,该请求不会携带认证信息,需要在Spring Security中放行所有OPTIONS请求:
修改configure(HttpSecurity http)方法,添加OPTIONS请求放行规则:

import org.springframework.http.HttpMethod;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    // 会自动使用上面定义的corsConfigurationSource Bean
    http.cors();
    // 放行所有OPTIONS预检请求
    http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
    http.authorizeRequests().antMatchers("/login").permitAll();
    http.authorizeRequests().antMatchers("/").permitAll();
    http.authorizeRequests().antMatchers("/api/teachers/**").hasAuthority("TEACHER");
    http.authorizeRequests().antMatchers("/api/students/**").hasAuthority("STUDENT");
    http.authorizeRequests().antMatchers("/api/**").hasAuthority("ADMIN");

    http.authorizeRequests().anyRequest().authenticated();
    http.addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtSecret));
    http.addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtSecret));
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

注意事项

  • 生产环境请将config.addAllowedOriginPattern("*")替换为你的前端实际域名,例如config.addAllowedOriginPattern("https://你的前端域名.com"),避免跨域配置过于宽松带来安全风险。
  • 如果使用的是低于Spring Boot 2.4的版本,可以将addAllowedOriginPattern替换为addAllowedOrigin。

内容的提问来源于stack exchange,提问作者user12296041

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:48:03