Spring Security静态内存用户登录失败问题求助
问题排查与解决
核心问题:登录表单输入框缺少name属性
Spring Security表单登录默认会从请求参数中获取username和password字段,但你的登录表单里,用户名、密码输入框仅设置了id,未添加name属性,导致Spring Security无法读取用户输入的账号密码,最终认证失败。
修复后的登录表单代码
修改login.html,为输入框补充对应的name属性:
<form class="row g-3 justify-content-center" th:action="@{perform_login}" method="post"> <div class="col-auto"> <input type="text" class="form-control" id="username" name="username" th:placeholder="#{name.user}" > </div> <div class="col-auto"> <input type="password" class="form-control" id="password" name="password" th:placeholder="#{name.pass}" > </div> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-3" th:text="#{add.user}"></button> </div> <div class="row"> <div class="col-auto"> <a href="http://localhost:8080/registration/" th:text="#{name.reg}">></a> </div> </div> </form>
额外排查点(若修复后仍异常)
- CSRF令牌验证:Spring Security默认启用CSRF保护,使用Thymeleaf时表单会自动生成CSRF令牌;若为普通HTML表单,需手动添加:
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" /> - 路径权限检查:虽然
loginProcessingUrl对应的/perform_login会被Spring Security自动允许访问,但可确认是否有其他拦截规则干扰该路径的访问。 - 密码编码器配置:你的配置中已正确使用
BCryptPasswordEncoder,内存用户密码也做了加密处理,这部分无需调整。
内容的提问来源于stack exchange,提问作者Niccolò Balzarotti
相关产品推荐
相关产品推荐

