Spring Boot 2.0.1未引入Spring Security却出现AJAX请求403错误求助
我来帮你分析下这个问题——虽然你没有手动引入Spring Security模块,但出现403 Forbidden确实是权限拦截导致的,下面是几个最可能的原因和对应的解决方案:
1. 间接引入了Spring Security依赖
你pom.xml里的spring-data-rest-hal-browser依赖,可能会间接引入Spring Security相关组件(比如spring-security-web和spring-security-config)。Spring Boot在检测到这些组件时,会自动启用默认的安全配置:默认启用CSRF保护,而AJAX POST请求如果没有携带CSRF令牌,就会被拦截返回403。
验证方法
运行Maven命令查看依赖树,确认是否存在Spring Security相关依赖:
mvn dependency:tree | grep spring-security
解决方案
方案A:排除间接引入的Spring Security
修改spring-data-rest-hal-browser的依赖配置,排除Spring Security组件:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-rest-hal-browser</artifactId> <exclusions> <exclusion> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> </exclusion> <exclusion> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> </exclusion> </exclusions> </dependency>
方案B:配置Spring Security允许请求
如果需要保留Spring Security(比如后续可能用到),可以添加一个安全配置类,关闭CSRF保护并允许所有请求:
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 关闭CSRF保护,允许所有请求访问 http.csrf().disable() .authorizeRequests() .anyRequest().permitAll(); } }
2. 跨域请求(CORS)未配置
如果你的前端页面和后端服务不在同一个端口/域名下(比如前端在localhost:3000,后端在localhost:8080),AJAX POST请求会触发浏览器的跨域检查,后端如果没有配置CORS支持,就会返回403。
解决方案
添加全局CORS配置类,允许跨域请求:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); // 生产环境建议替换为具体的前端域名,比如http://localhost:3000 config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
或者在你的控制器方法上直接添加@CrossOrigin注解,单独允许该接口的跨域请求。
3. 自定义拦截器拦截了请求
检查你的项目中是否存在自定义的HandlerInterceptor或过滤器,这些组件可能会拦截POST请求并返回403。可以查看项目中的配置类,确认是否有注册相关拦截器的逻辑。
内容的提问来源于stack exchange,提问作者ekka

