authentication - 登录尝试失败后将用户名保留在表单输入字段中(Java/Spring-security)

标签 authentication spring-security thymeleaf

我已成功设置 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 并在重定向之前将我想保留的请求参数(usernameremember-me)添加到 URL .

我很想知道是否有更好的方法来做到这一点。

关于authentication - 登录尝试失败后将用户名保留在表单输入字段中(Java/Spring-security),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31660208/

相关文章:

php - Codeigniter Auth Library - 特定组的用户名公共(public)配置文件,对其他组禁用

jquery - 使用 jquery ajax 部署身份验证

spring - JHipster OAuth2 服务器 -/oauth/authorize 的登录页面

java - ExceptionTranslator 的异常不会返回到 flex

java - 无法显示表单支持 bean 的验证错误

java - Springboot/Thymeleaf 在每个页面上从模型中检查当前用户

jquery - 如何在 jQuery 中访问模型属性

python - 是否有任何内置的 django 身份验证和 acl=访问控制列表库?

security - 他们的应用程序之间的谷歌身份验证和授权

java - Spring Security通过过滤器验证验证码具有错误的值