Spring Security 登录失败后弹窗提示的一种方案

Spring Security 登录失败后弹窗提示的一种方案

解决方案基于 Thymeleaf 页面,优点是通过检测 session 值的方式而不是 url 路径参数,避免了刷新页面时重复弹出警告的现象。

  1. 自定义登录失败处理器,向 session 写入 error 属性:

    @Component
    public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                            AuthenticationException exception) throws IOException {
            request.getSession().setAttribute("error", exception.getMessage());
            response.sendRedirect("/login");
        }
    }
    
  2. 在 Spring Security 设置类使用这个处理器:

    http.formLogin(f -> f.loginPage("/login").failureHandler(failureHandler).permitAll());
    
  3. 在你的登录控制器里写入检测 error 属性是否存在的逻辑:

    @GetMapping("/login")
    public String login(Principal principal, Model model, HttpSession session) {
        if (principal != null) {
            return "redirect:/";
        }
        Object errorMessage = session.getAttribute("error");
        if (errorMessage != null) {
            model.addAttribute("error", errorMessage.toString());
            session.removeAttribute("error");
        }
        return "front/login";
    }
    
  4. 在 Thymeleaf 页面根据 error 属性是否存在展示弹窗:

    <!-- 这里用了 SweetAlert2 -->
    <script th:if="${error}" type="text/javascript">
        Swal.fire({
        icon: 'error',
        title: '登录失败',
        text: '用户名或密码错误!'
    });
    </script>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值