Angular5向SpringBoot后端发POST请求遇CORS及SpringSecurity问题求助
解决Angular 5 POST请求到Spring Boot的CORS预检重定向问题
从你的报错信息和代码来看,问题的核心是Spring Security拦截了CORS预检请求(OPTIONS方法)并进行了重定向,而CORS规则明确禁止预检请求存在重定向操作,因此触发了报错。
问题根源
浏览器发送跨域POST请求前,会自动发起一个OPTIONS预检请求,用来验证后端是否允许该跨域请求。你的Spring Security配置中,仅放行/login/**路径的请求,其他所有请求(包括OPTIONS预检请求)都要求身份认证,因此OPTIONS请求被拦截后会重定向到登录页,这直接违反了CORS规范,导致浏览器报错。
解决方案
你需要修改Spring Security的配置,合理放行必要的请求,同时保证CORS配置正常生效:
方案1:全局放行所有OPTIONS预检请求
修改SecurityConfig中的configure(HttpSecurity http)方法,添加对OPTIONS请求的全局放行:
import org.springframework.http.HttpMethod; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() // 允许所有OPTIONS预检请求通过 .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .antMatchers("/login/**").permitAll() .anyRequest().authenticated() .and() .formLogin().loginPage("/login") .and().exceptionHandling().accessDeniedPage("/forbidden"); }
方案2:启用Spring Security的CORS专属配置
这种方式更规范,能和你在RestController上添加的@CrossOrigin注解配合生效:
import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import java.util.List; // 在SecurityConfig中添加CORS配置Bean @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("http://localhost:4200")); // 指定允许的前端域名 config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(List.of("*")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } // 修改configure方法,启用CORS支持 @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .cors() // 启用Spring Security的CORS支持 .and() .authorizeRequests() .antMatchers("/login/**").permitAll() .anyRequest().authenticated() .and() .formLogin().loginPage("/login") .and().exceptionHandling().accessDeniedPage("/forbidden"); }
额外注意点
你的内存身份认证配置中,密码没有进行加密处理,但你已经配置了BCryptPasswordEncoder,这会导致后续登录失败,需要修改为加密后的密码:
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin") .password(bCryptPasswordEncoder().encode("1234")) // 对密码进行BCrypt加密 .roles("ADMIN"); }
验证
修改配置后重启后端服务,再次发送Angular的POST请求,此时OPTIONS预检请求会正常通过,POST请求也能顺利到达AdministrateursRestController完成处理。
内容的提问来源于stack exchange,提问作者beyyato abdellah
相关产品推荐
相关产品推荐

