JAVA用户名密码输入错误3次,锁定账号30分钟简单实现(不操作数据库)

纯java代码实现登陆次数验证,登陆错误5次之后锁定30分钟:https://blog.csdn.net/weixin_41996632/article/details/85675410
在Java项目中使用SpringSecurity实现输入密码错误过多锁定用户的功能:
https://www.yisu.com/zixun/218605.html

public Object login(User user,HttpSession session) throws Exception {
        String username = user.getUsername();
        String password = user.getPassword();
        if(!checkLock(session, username)) {
            throw new CustomException(StatusCode.ERROR_CODE,"该账号已被锁定");
        }
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)) {
            throw new CustomException(StatusCode.ERROR_CODE, "用户名和密码不能为空!");
        }
        User  u = getByUsername(username);
        if (u == null) {
            throw new CustomException(StatusCode.ERROR_CODE, "用户名不存在!");
        }
        if(!MD5Util.checkpassword(password, u.getPassword())) {
            //新增登录失败记录
            addFailNum(session, username);
            throw new CustomException(StatusCode.ERROR_CODE, "用户名或密码错误!");
        }
      //清空登录失败记录
        cleanFailNum(session, username);
 
    ......
}
/**
     * 校验用户登录失败次数
     * @param session
     * @param username
     * @return
     */
    public boolean checkLock(HttpSession session,String username) {
        Object o = session.getServletContext().getAttribute(username);
        if(o==null) {
            return true;
        }
        HashMap<String,Object> map  = (HashMap<String, Object>) o;
        int num  = (int) map.get("num");
        Date date = (Date) map.get("lastDate");
        long timeDifference = ((new Date().getTime()-date.getTime())/60/1000);
        if(num>=3&&timeDifference<30) {
            return false;
        }
        return true;
    }
    /**
     * 新增用户登录失败次数
     * @param session
     * @param username
     */
    public void addFailNum(HttpSession session, String username) {
        Object o = session.getServletContext().getAttribute(username);
        HashMap<String,Object> map = null;
        int num= 0;
        if(o==null) {
            map = new HashMap<String,Object>();
        }else {
            map  = (HashMap<String, Object>) o;
             num  = (int) map.get("num");
             Date date = (Date) map.get("lastDate");
             long timeDifference = ((new Date().getTime()-date.getTime())/60/1000);
             if(timeDifference>=30) {
                 num=0;
             }
        }
        map.put("num", num+1);
        map.put("lastDate", new Date());
        session.getServletContext().setAttribute(username, map);
    }
    /**
     * 清理用户登录失败的记录
     * @param session
     * @param username
     */
    public void cleanFailNum(HttpSession session, String username) {
        session.getServletContext().removeAttribute(username);
    }
posted @ 2022-08-26 11:47  西门长海  阅读(1118)  评论(0编辑  收藏  举报