Spring Security问题:注册控制器PostMapping注解的addUser方法未被调用
问题原因及修复方案
1. 解决接口被Spring Security拦截的核心问题
当前Security配置中/registration路径的访问规则配置错误:
原配置.antMatchers("/registration").not().fullyAuthenticated()的含义是「仅非完全认证的用户可访问」,未登录的匿名用户并不匹配该规则,因此注册POST请求会命中后续anyRequest().authenticated()的认证要求,被拦截后重定向到登录页。
修改WebSecurityConfig类的configure方法,直接给注册路径放行即可:
@Override protected void configure(HttpSecurity httpSecurity) throws Exception{ httpSecurity .csrf() .disable() .authorizeRequests() .antMatchers("/css/**", "/js/**", "/images/**").permitAll() // 修正注册路径的规则,全量放行匿名访问 .antMatchers("/registration").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/") .permitAll() .and() .logout() .permitAll() .logoutSuccessUrl("/"); }
同时建议统一路径写法避免匹配问题:把模板里的th:action="@{/registration/}"末尾的斜杠删除,改为th:action="@{/registration}",和控制器的@PostMapping("/registration")路径保持一致。
2. 修复User实体类的接口实现错误
当前User类实现UserDetails接口的四个状态方法全部返回false,会导致后续即便注册成功也无法正常登录:
// 原错误实现 @Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return false; }
将这四个方法的返回值全部改为true即可,后续如果需要做账号过期、锁定等功能再按需调整逻辑。
3. 可选优化点
- 注册页面的密码输入框当前
type="text"会明文显示密码,建议改为type="password" - 可以在Security配置中显式指定登录请求的参数名,和表单项对应,避免后续登录时参数映射错误
addUser方法触发场景
当客户端发送路径匹配/registration的POST请求、且请求参数能正常绑定到User实体对象时,该方法就会被触发,依次完成表单校验、密码一致性校验、用户信息入库的逻辑。
内容的提问来源于stack exchange,提问作者GrigoryKrasovsky
相关产品推荐
相关产品推荐

