SpringBoot禁用CSRF后POST请求仍被禁止,配置是否有误?
问题分析与解决方案
问题根源
你配置的formLogin().loginProcessingUrl("/public/api/access/login/signin")会让Spring Security的**表单登录过滤器(FormLoginAuthenticationFilter)**接管该路径的POST请求,导致你自己编写的SigninController中的login方法根本不会被执行。
这个过滤器默认只处理application/x-www-form-urlencoded格式的表单请求,而你的测试用的是application/json格式,过滤器无法解析JSON中的用户名密码,直接触发认证失败,返回403禁止状态。
修复方案
因为你已经手动实现了登录逻辑,不需要Spring Security的表单登录功能,直接移除formLogin相关配置即可:
修改后的HttpSecurity配置:
http.csrf().disable() .authorizeHttpRequests() .requestMatchers(maintenanceRequestMatcher).denyAll() .antMatchers("/public/**").permitAll() .antMatchers("/auth/**").authenticated() .antMatchers("/auth/api/superadmin/**").hasAnyRole("SUPERADMIN") .antMatchers("/auth/api/admin/**").hasAnyRole("SUPERADMIN","ADMIN") .antMatchers("/auth/api/staff/**").hasAnyRole("SUPERADMIN","ADMIN","STAFF") .antMatchers("/auth/api/standarduser/**").hasAnyRole("SUPERADMIN","ADMIN","STAFF","STANDARDUSER") .anyRequest().authenticated() .and() .httpBasic();
验证说明
移除formLogin配置后,/public/api/access/login/signin的POST请求会直接路由到你自己的控制器方法,由你手动调用authenticationManager.authenticate()完成认证,此时JSON格式的请求就能正常处理,测试会返回200状态。
内容的提问来源于stack exchange,提问作者Discipulos
相关产品推荐
相关产品推荐

