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

Angular 10集成Spring Security自定义登录页时遭遇CORS跨域问题

解决Spring Boot + Angular的CORS跨域问题

看起来你遇到的是典型的跨域资源共享(CORS)配置问题——你的Spring Boot后端还没正确配置允许来自Angular前端的跨域请求。虽然你在WebSecurityConfig里加了http.cors(),但缺少具体的CORS规则配置,导致预检请求(OPTIONS)没有得到正确的响应头。

下面是具体的修复步骤:

1. 添加全局CORS配置Bean

在你的WebSecurityConfig类中,添加一个CorsConfigurationSource的Bean,明确指定允许的源、HTTP方法、请求头以及是否允许携带凭证:

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.CorsConfigurationSource;
import java.util.Arrays;

// ... 其他已有代码

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    // 允许你的Angular前端地址,默认是http://localhost:4200
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    // 允许所有常用的HTTP方法,包括预检请求的OPTIONS
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    // 允许的请求头,包括认证相关的和内容类型
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With"));
    // 如果你的请求需要携带Cookie或认证信息,设置为true
    configuration.setAllowCredentials(true);
    // 预检请求的缓存时间,减少OPTIONS请求的频率
    configuration.setMaxAge(3600L);

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 对所有路径应用这个CORS配置
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

2. 调整Spring Security的配置顺序

确保cors()在csrf()之前配置,这样CORS规则会优先生效:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
        .and()
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/user/save","/user/login", "/admin/**").permitAll()
            .anyRequest().authenticated()
        .and()
        .formLogin().permitAll()
        .and()
        .logout().permitAll();
}

3. 修复Angular请求的判断逻辑

你的后端login接口返回的是boolean类型,而不是带有status属性的响应对象,所以前端的判断需要调整:

public doLogin(){
    this.userLogin.username=this.loginForm.get("username").value;
    this.userLogin.password=this.loginForm.get("password").value;
    console.log(this.userLogin);
    return this.http.post<boolean>("http://localhost:8080/user/login",this.userLogin).subscribe((response) => {
        if (response) {
            console.log('login successfully');
        } else {
            console.log('Invalid username or password');
        }
    }, (error) => {
        // 处理请求失败的情况,比如CORS错误、网络问题等
        console.error('Login request failed:', error);
    });
}

为什么之前的配置不生效?

当你调用http.cors()时,Spring Security会寻找CorsConfigurationSource类型的Bean。如果没有定义这个Bean,它会使用默认的配置,而默认配置不会允许你的Angular前端地址,导致预检请求被拒绝,从而出现Access-Control-Allow-Origin头缺失的错误。

完成以上修改后,重启你的Spring Boot后端,然后在Angular中测试登录请求,应该就能解决CORS问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:57:49