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

Spring Boot中Spring Security配置Admin角色访问接口报403问题求助

问题原因分析
  • 核心原因是Spring Security默认开启了CSRF(跨站请求伪造)防护机制,所有非GET、HEAD、TRACE、OPTIONS类的请求(包含你用到的POST、PUT、DELETE)都会校验CSRF令牌,调用接口时没有携带合法令牌就会直接返回403错误。
  • 你的权限配置本身没有问题,GET类型的查询接口可以正常访问就说明角色、权限匹配逻辑是生效的。
解决方案

如果你的项目是前后端分离架构、接口仅作为API服务对外提供,直接在安全配置中关闭CSRF防护即可,修改SecurityConfiguration类的configure(HttpSecurity http)方法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/employee/createEmployee", "/employee/createEmployees", "/employee/updateEmployee/**", "/employee/deleteEmployee/**").hasRole("Admin")
            .antMatchers("/employee/getEmployee/**", "/employee/getAllEmployees").hasAnyRole("Admin", "User")
            .and().httpBasic()
            // 新增这行关闭CSRF防护
            .and().csrf().disable();
}

如果你需要保留CSRF防护能力,每次调用POST/PUT/DELETE接口时,需要先从响应头或Cookie中获取CSRF令牌,携带在请求头X-CSRF-TOKEN中再发起请求即可。

验证说明

修改配置后使用John账号调用增删改类接口,就可以正常返回对应状态码,不会再出现403错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:06:03