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

Spring Security 6项目CRUD删除操作遇跨域与401权限问题求助

问题解决思路

一、解决CORS跨域拦截问题

在Spring Security 6中,请求会先经过Security过滤器链,单纯配置Spring MVC的CORS可能不生效,需要在SecurityFilterChain中显式配置:

  1. 定义CORS配置源
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    // 替换为你的前端实际域名,比如localhost:4200
    config.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    // 包含DELETE方法,覆盖预请求和实际请求的方法限制
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    // 允许认证头和内容类型头,适配认证和请求体需求
    config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
    // 允许跨域请求携带凭证(Cookie、Token等)
    config.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 对所有接口应用该CORS规则
    source.registerCorsConfiguration("/**", config);
    return source;
}
  1. 在SecurityFilterChain中启用CORS
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        // CORS配置要放在CSRF之前,保证过滤器顺序正确
        .cors(cors -> cors.configurationSource(corsConfigurationSource()))
        .csrf(csrf -> csrf.disable()) // 前后端分离场景通常关闭CSRF,或按需配置令牌
        .authorizeHttpRequests(auth -> auth
            // 给删除接口配置对应权限,根据你的业务调整角色/权限
            .requestMatchers("/angular/deleteUser").hasAnyRole("ADMIN")
            .anyRequest().authenticated()
        );
    return http.build();
}

注意:你提供的前端请求URL末尾多了一个},需修正为http://localhost:8080/angular/deleteUser?id=3,语法错误也可能引发异常。

二、解决Postman 401 Unauthorized问题

Postman返回401说明请求未携带有效认证信息,按以下方向排查:

  • 若用Session认证:先通过登录接口获取Session Cookie,在删除请求的Cookie中携带该值。
  • 若用JWT认证:在请求头中添加Authorization: Bearer <你的JWT令牌>,令牌需从登录接口获取。
  • 检查Security配置中/angular/deleteUser的权限规则,确认你使用的测试用户拥有对应角色(比如配置了hasRole("ADMIN"),就要用ADMIN角色用户登录)。

额外排查点

  1. 检查控制器方法:确保deleteUser接口用@DeleteMapping注解,参数绑定正确(比如@RequestParam("id") Long id)。
  2. 前端请求配置:Angular的HttpClient请求需开启withCredentials: true,否则跨域时不会自动携带认证凭证(Cookie/Token),导致后端无法识别用户身份。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:06:11