Spring Boot+Angular租车应用postCar接口CORS及JWT认证问题求助
解决Spring Boot + Angular租车应用的CORS拦截问题
你的问题核心是Spring Security的拦截优先级高于Controller的@CrossOrigin配置,同时带Authorization头的请求会触发OPTIONS预检请求,而你的Security配置未放行这类请求,最终导致CORS拦截。以下是具体解决步骤:
1. 统一配置Spring Security的CORS规则
在WebSecurityConfig中添加CORS配置Bean,并启用CORS支持:
@Configuration @EnableWebSecurity @EnableMethodSecurity @RequiredArgsConstructor public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final JwtAuthenticationFilter jwtAuthenticationFilter; private final UserService userService; // 新增CORS配置Bean @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); // 生产环境请替换成你的Angular实际域名,比如http://your-frontend-domain.com config.setAllowedOrigins(Collections.singletonList("http://localhost:4200")); // 允许所有HTTP方法,包括OPTIONS预检请求 config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许Authorization和Content-Type头(JWT和表单/JSON请求需要) config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type")); // 允许携带凭证(如果需要) config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } @Override protected void configure(HttpSecurity http) throws Exception { http.cors(withDefaults()) // 启用上面配置的CORS规则 .csrf().disable() .authorizeRequests(request -> request.antMatchers("/api/auth/**").permitAll() .antMatchers("/api/admin/**").hasAnyAuthority(UserRole.ADMIN.name()) .antMatchers("/api/customer/**").hasAnyAuthority(UserRole.CUSTOMER.name()) .anyRequest().authenticated()) .sessionManagement(manager -> manager.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } // 其他Bean保持不变... }
2. 让JWT过滤器跳过OPTIONS预检请求
OPTIONS请求是浏览器自动发送的,不会携带JWT Token,需要在JwtAuthenticationFilter的doFilterInternal方法开头跳过这类请求:
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 跳过OPTIONS预检请求 if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); return; } // 原来的JWT校验逻辑... }
3. 可选:移除Controller上的@CrossOrigin(避免冲突)
既然已经在Security层面统一配置了CORS,建议移除AdminController上的@CrossOrigin注解,避免多重配置导致的冲突。
额外检查点
- 确认Angular端的
StorageService.getToken()能正确获取到有效的JWT Token,否则即使CORS问题解决,也会出现401认证失败。 - 生产环境不要用
allowedOrigins = "*",必须指定具体的前端域名,避免安全风险。
内容的提问来源于stack exchange,提问作者brkozkn999
相关产品推荐
相关产品推荐

