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

Spring Security自定义UserDetailsService未触发调用问题排查

问题排查与解决

看起来你的登录请求根本没触发对应的Spring Security认证流程,所以loadUserByUsername方法才没被调用。我帮你梳理几个关键问题:

1. 登录表单输入框缺少name属性

你的管理员登录表单里,用户名和密码的input标签只有id属性,没有name属性:

<input type="text" class="form-control" placeholder="Email or Mobile" id="username">
<input type="password" class="form-control" placeholder="" id="password">

浏览器提交表单时,只会携带带有name属性的字段值。你在Spring Security配置里指定了username-parameter="username"和password-parameter="password",所以必须给input加上对应的name属性:

<input type="text" class="form-control" placeholder="Email or Mobile" id="username" name="username">
<input type="password" class="form-control" placeholder="" id="password" name="password">

这是最核心的问题——没有name属性的话,后端根本接收不到用户名和密码,认证流程直接跳过。

2. login-processing-url不在对应http区段的pattern范围内

你的管理员http区段配置的拦截规则是pattern="/admin/**",但登录处理URL是/authenticateAdmin,这个路径不在/admin/**的覆盖范围内,所以该http区段不会处理这个请求。同理,学生端的/authenticateStudent也不在/student/**的范围内。

需要把登录处理URL修改为对应pattern下的路径:

<!-- 管理员端的login-processing-url -->
<form-login login-page="/adminLogin" default-target-url="/admin/home" 
           authentication-failure-url="/views/homePages/adminHome" 
           username-parameter="username" password-parameter="password" 
           login-processing-url="/admin/authenticateAdmin" />

<!-- 学生端的login-processing-url -->
<form-login login-page="/studentLogin" default-target-url="/student/home" 
           authentication-failure-url="/studentLogin" 
           username-parameter="username" password-parameter="password" 
           login-processing-url="/student/authenticateStudent" />

同时要同步修改登录表单的action属性:

<!-- 管理员表单的action -->
<form class="login-form" action="/admin/authenticateAdmin" method="POST">

3. 额外注意:重复的Bean定义

你的AdminAuth类上标注了@Service注解,但又在xml中配置了<beans:bean id="adminAuthService" class="security.AdminAuth"/>,这会导致Spring容器中出现两个相同类型的Bean,可能引发冲突。建议二选一:要么保留@Service并移除xml中的Bean定义,要么移除@Service保留xml配置。

把这些修改完成后,再测试登录流程,loadUserByUsername方法应该就能正常被调用了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:24:17