Java实现登录密码输错5次锁账号

这里的登录是Springboot集合jwt完成的
以下是代码实现

Controller

@RestController
@RequestMapping("/demo")
public class LoginController {

@Autowired
private DemoService demoService;

@PostMapping("/login")
    public JwtVO Login(@RequestBody LoginVO loginVO, HttpServletRequest request){
        JwtToken jwtToken = demoService.loginDemo(loginVO, request);
        return generateJwt(jwtToken, request);
    }

   /**
     * 生成Jwt
     * @param jwtToken
     * @param request
     * @return
     */
    private JwtVO generateJwt(JwtToken token, HttpServletRequest request){
        return JwtVO.builder().token(token.getToken())
                .expireTime(token.getAccessToken().getExpireTime().getEpochSecond())
                .refreshExpireTime(token.getRefreshToken().getExpireTime().getEpochSecond()).build();
    }
    
}

Service层

@Service
public class DemoServiceImpl implements DemoService {
	@Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtTokenComponent jwtTokenComponent;
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    // 定义一个记录错误次数的字符串前缀
	private final String ERRORSTR = "login_error_times_";

 	public JwtToken loginDemo(LoginVO loginVO, ClientEnum client, HttpServletRequest request) {
 	// 获取IP,这个百度有很多
	String keyStr = ERRORSTR+WebUtils.getClientIp(request);
        if(redisTemplate.hasKey(keyStr)) {
            // 登录时候先判断是否有登录错误的计数
            int errorNum = Integer.valueOf((String) redisTemplate.opsForValue().get(keyStr));
            if(errorNum==5){
            	// 这里是自定义一个runtimeException
                throw new DemoException("登录错误次数超过5次,请1小时后再试");
            }
        }
	// 这边可以根据自己需求做一些账密校验
	// 这里的PASSWORD,是通过操作数据库查出的账户密码
	if(!passwordEncoder.matches(loginVO.getPassword(), PASSWORD)){
			// 该方法为记录错误登录次数,单写在下面
            loginErrorRecord(keyStr,request);
            throw new DemoException("账户或密码不正确");
        }
	
	// 这里的userId是通过操作数据库,账密校验通过后查出的用户id
	jwtToken = jwtTokenComponent.generate(DemoAccountToken
                .builder().userId(userId).userName(loginVO.getUserName).build());
        // 删除登录错误的记录
        redisTemplate.delete(keyStr);
        return jwtToken;
 	}

   /**
     * 记录登录错误次数
     * 
     * @param keyStr
     * @param request
     */
    private void loginErrorRecord(String keyStr,HttpServletRequest request) {
        if(redisTemplate.hasKey(keyStr)){
            int errorNum = Integer.valueOf((String)redisTemplate.opsForValue().get(keyStr));
            redisTemplate.opsForValue().set(keyStr, errorNum+1,18000, TimeUnit.SECONDS);
        }else{
            redisTemplate.opsForValue().set(keyStr, 1,18000, TimeUnit.SECONDS);
        }
    }
    
}

你可能感兴趣的:(菜鸟开发日记,java,spring,boot,开发语言)