需求

登录模块我们需要限制非法用户试密码的次数,此次需求为限制5次,锁定用户30分钟

解决方案

利用redis,登录一下,可以使用用户的账号作为key,存到redis中,每次登录value+1,每次登录都查redis,看某一用户的value是否大于等于5,如果是,那么就直接返回对应的异常信息和code码

代码

后端

public String loginCommit(String email, String pwd, String reqid, Model model, HttpServletResponse response,
			String re, HttpServletRequest request) {
	
		int time = 1;
		String times = stringRedisTemplate.opsForValue().get("login_error_times_" + email);
		//密码错误5次
		if (StringUtils.isNotBlank(times) && Integer.parseInt(times) >= 5) {
			return returnLogin(2014);
		try {
			// 登录操作
		
		}catch (GeneralException e) {
			// 登录失败5次,将锁定30分钟
			if (e.getCode() == 2004) {
				if (StringUtils.isNotBlank(times)) {
					time = Integer.parseInt(times) + 1;
				}
				stringRedisTemplate.opsForValue().set("login_error_times_" + email, time + "", 30, TimeUnit.MINUTES);
				model.addAttribute("login_error_times", time);
				return returnLogin( 2004);
			}

前端JSP

 if (parseInt("${errorCode}") === 2004) {
            $("#login_err_msg_pwd").text('<fmt:message key="login.account_pwd_error"/>' + '${login_error_times}' + ',5次后账号将锁定30分钟').show();
            resetAllErrMsg = true;
        }
      
        if (parseInt("${errorCode}") === 2014) {
            $("#login_err_msg_pwd").text('密码已错误5次,30分钟后再试').show();
        }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐