我已成功设置 Spring-Boot MVC 应用程序使用 Spring-Security和基于表单的身份验证。我已经使用 thymeleaf 实现了自定义登录表单,基本上看起来像:
<form th:action="@{/login}" method="POST">
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
<button type="submit">Log in</button>
</form>
表单在扩展 WebMvcConfigurerAdapter
的类的 addViewControllers
方法中注册为简单的“View Controller”,例如:
public class LoginController extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login/login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
到目前为止,这是有效的。有一件事困扰着我:登录尝试失败后,应用程序返回到登录表单(这很好),但两个字段都被清除了。我想将用户名保留在输入字段中(以防密码拼写错误)。
我试过了
<input type="text" id="username" name="username" th:value="username"/>
但这并没有帮助。
有没有办法从 thymeleaf 模板中的不成功尝试中获取用户名?我需要为此编写一个显式 Controller 吗?
最佳答案
这个问题的症结在于 SimpleUrlAuthenticationFailureHandler
,默认的 AuthenticationFailureHandler
,执行重定向 - 因此请求参数(包括用户名)将无法用于登录形式。
奇怪的是,对于如此明显的事情,似乎没有一个优雅的解决方案。
如果您只需要保留用户名,那么一个快速但不是很令人满意的选项是在模板中使用 SPRING_SECURITY_LAST_EXCEPTION.authentication.principal
(尽管请注意,它在第一个为 null访问页面)。
但是,如果您使用“记住我”复选框,您会发现同样的问题。
我最终扩展了 SimpleUrlAuthenticationFailureHandler
并在重定向之前将我想保留的请求参数(username
和 remember-me
)添加到 URL .
我很想知道是否有更好的方法来做到这一点。
关于authentication - 登录尝试失败后将用户名保留在表单输入字段中(Java/Spring-security),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31660208/