首页 > 解决方案 > Spring boot Authentication Failure Handler - 自定义,没有额外的 url 或查询参数

问题描述

我当前的 Spring Boot Login 实现如下:

登录.html:

<div class="error-message m-l-4" th:if="${errorMessage}" th:text="${errorMessage}"></div>

WebSecurityConfigurerAdapter - 配置方法:

formLogin().failureUrl("/login-error")

请求映射器:

@RequestMapping("/")
public class Root {
    @GetMapping("login")
    public ModelAndView getLoginView(ModelMap mav) {    
        return new ModelAndView("login", mav);
    }
    
    @GetMapping("login-error")
    public RedirectView setErrorMessage(RedirectAttributes attributes) {
        attributes.addFlashAttribute("errorMessage", "Username or Password is invalid");
        return new RedirectView("login");
    }
}

当用户输入无效凭据时,上述工作完美,错误显示在 HTML 上。但是,有没有办法实现相同的结果,但摆脱额外的目录 /login-error?尽管重定向到出现错误的登录页面,但我不希望它可以访问。我试图翻译自定义 AuthenticationFailureHandler (.failureHandler(new CustomAuthenticationFailureHandler())) 以产生相同的效果,但我只能返回 JSON 而不是 HTML。基本上,我想要与 Instagram 登录页面完全相同的行为。

请参阅按顺序排列的页面,并在刷新后返回到第 1 页的确切页面: 第 1 页 第 2 页 - 按登录 第 3 页 - 显示错误 第 4 页 - 单击刷新

标签: spring-bootthymeleafforms-authentication

解决方案


推荐阅读