Spring Boot登录接口Postman调用返回403 Forbidden错误排查
问题原因
- 核心原因1:安全配置类未正确生效,你写的CSRF禁用、路径放行规则没有被Spring Security加载。默认配置下Spring Security会开启CSRF防护,所有非GET、HEAD、TRACE的请求如果没有携带合法CSRF令牌会被直接拦截返回403。配置不生效通常是两个原因:一是部分低版本Spring Boot中
@EnableWebSecurity不会自动附带@Configuration注解,配置类不会被Spring容器识别;二是配置类所在包不在主启动类的扫描范围内。 - 核心原因2:AuthenticationManager Bean定义错误。你代码中定义该Bean的方法名为
AuthenticationManagerBean(首字母大写A),但父类WebSecurityConfigurerAdapter中需要重写的方法是authenticationManagerBean(首字母小写a),你没有正确重写父类方法,导致认证管理器没有被正确注册到容器,认证流程被拦截。 - 次要原因:你在配置用户详情服务时,没有显式关联你定义的
BCryptPasswordEncoder,即使403问题修复后也会出现密码校验不通过的401错误;同时CORS配置不完整,跨域场景下OPTIONS预检请求会被拦截。
修复步骤
- 修正安全配置类代码,补全注解、修正方法名、完善配置逻辑:
@Configuration // 补全配置注解,保证类被Spring识别 @EnableWebSecurity @CrossOrigin public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private IEmployeeRepository employeeRepository; @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(username -> employeeRepository.findByEmail(username) .orElseThrow(() -> new UsernameNotFoundException("User " + username + " not found. "))) // 显式指定密码编码器,避免密码校验逻辑错误 .passwordEncoder(passwordEncoder()); } @Bean @Override // 加上重写注解,方法名改为首字母小写,正确重写父类方法 public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 显式禁用默认表单登录、基础认证、登出接口,避免不必要的拦截 http.formLogin().disable() .httpBasic().disable() .logout().disable(); http.authorizeRequests().anyRequest().permitAll(); } // 补全CORS配置,避免跨域预检请求被拦截 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOriginPatterns(Collections.singletonList("*")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Collections.singletonList("*")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
- 检查包路径:确认
ApplicationSecurityConfig类位于Spring Boot主启动类所在包的同级或子级目录下,保证能被组件扫描到。 - 校验数据与请求参数:
- 确认数据库中存储的用户密码是通过
BCryptPasswordEncoder加密后的密文,不是明文 - Postman发起请求时,设置请求头
Content-Type: application/json,请求体使用JSON格式传入合法的email、password参数
- 确认数据库中存储的用户密码是通过
验证
重启项目后重新发起POST请求调用/login接口,即可正常进入认证逻辑,认证成功返回200和对应令牌,密码错误返回401状态码。
内容的提问来源于stack exchange,提问作者renad sahal
相关产品推荐
相关产品推荐

