用户密码加密解密:
这个管理系统用户密码是使用springscurity的BCcryPasswordEncoder().encode进行加密;当然在登录需要进行解密在login接口下需要使用!bCryptPasswordEncoder.matches进行解密。
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
public static void main(String[] args) {
String encode = new BCryptPasswordEncoder().encode("123456");
System.out.println(encode);
}
判断密码正确是否后的操作:
解密后判断密码是否正确,如果密码正确就直接登录成功,反之密码错误后,就会判断您具体登录几次,而我们需要实现登录密码错误3次后需要等待30秒才能再次登录。因此需要以什么方式来判断您具体登录几次,我的方式是通过在user表中建立一个user_loginAttempts的字段,在当密码错误时,我们就向数据库增加1:
//增加登陆次数
@Update("UPDATE user SET user_loginAttempts = user_loginAttempts + 1 WHERE user_id = #{userId}")
void incrementLoginAttempts(Integer userId);
//判断密码是否正确
if(!bCryptPasswordEncoder.matches(userParam.getPassword(), selectByName.getPassword())) {
//修改登录次数
//查询登录次数
Integer loginAttempts = userService.selectloginAttemptsByUserName(res.getUsername());
//增加登陆次数
userService.incrementLoginAttempts(res.getUserId());
我们的数据库设置默认为0,因此点击一次登录错误后,就需要进行判断您还有几次登录机会;of course在点击一次后在页面就会弹出您还有两次机会;第一次和第二次错误判断如下:
if (res.getUserLoginAttempts() == 1){
return Result.error("-1", "Password error!You have one more opportunities to log in");
}else {
return Result.error("-1", "Password error!You have two more opportunities to log in");}
再次点击后就会弹出还有一次机会;
那么你如果下一次再次登录错误就达到了三次错误了,So就需要考虑以什么方式来解决等待30秒才能登录成功这个问题。我使用比较简单的一种方式:在user表中建立了一个记载第三次错误登录的字段user_loginLastTime。那么第三次错误了就将具体时间写入mysql;好在第四次登录的时候就需要等待30秒才能登录了。
第三次登录错误:
if(res.getUserLoginAttempts() == 2){
res.setUserLoginLastTime(LocalDateTime.now());
userService.updateuserLoginLastTime(res);
return Result.error("-1","You will need to wait 30 seconds before logging in");
}
第四次登录错误:
直接是以当前和第三次存储时间进行比较
if(res.getUserLoginAttempts()>2){
LocalDateTime lastLoginTime = res.getUserLoginLastTime();
LocalDateTime currentTime = LocalDateTime.now();
//判断
Duration duration = Duration.between(lastLoginTime,currentTime);
if (duration.getSeconds()<30){
long i = 30;
return Result.error("-1", "You've been waiting "+(i-duration.getSeconds())+" seconds");
}else {
userService.updateLoginAttemptsZero(res.getUserId());
return Result.error("-1","Login restrictions reset");
}
}