java登录锁定_java做帐户登录失败锁定

本文介绍了一种使用Java实现的登录系统中账户连续失败登录5次后锁定30分钟的方法。通过创建UserErrorLoginRecord实体类记录登录时间和错误次数,并使用HashMap存储。在登录控制器中,检查登录错误次数,若超过4次则锁定账户,30分钟后自动解锁。作者建议可以使用Redis进一步优化实现。
摘要由CSDN通过智能技术生成

对于连续失败登录应用系统5次的帐号,需锁定该帐号至少30分钟不允许登录。

这里也用简单的map集合进行判定,功能能实现,但并不是很完美,不用更改数据库的表字段

1、首先建立一个用户登陆失败的实体类

public class UserErrorLoginRecord {

//登录时间

private Date longinTime;

//错误次数

private Integer errorNum;

}

2、再登陆的contorller里

private static Map LOG_MAP = new HashMap();

3、再判断用户登陆系统的具体方法里

UserErrorLoginRecord userError = null;

boolean flag = true;  //默认每次进入都是true,当输入失败5次后,设置为false,直接锁定当前账户30分钟。

用户每次登陆失败就进行存储一次,如下

userError = LOG_MAP.get(username);

if (userError == null) {

userError = new UserErrorLoginRecord();

userError.setErrorNum(1);

userError.setLonginTime(new Date());

LOG_MAP.put(username, userError);

}else{

int loginNumber = userError.getErrorNum();

在Spring Security,可以通过配置账户锁定来增强安全性。当用户连续输入错误的密码时,可以将其账户锁定一段时间,以防止恶意攻击。具体实现方式如下: 1. 在数据库添加一个字段用于记录账户是否被锁定。 2. 在Spring Security的配置文件添加如下代码: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .permitAll() .and() .rememberMe() .key("uniqueAndSecret") .tokenValiditySeconds(86400) .and() .exceptionHandling().accessDeniedPage("/403") .and() .csrf().disable(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 3. 在UserDetailsService的实现添加如下代码: ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found"); } if (user.isLocked()) { throw new LockedException("User account is locked"); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, !user.isLocked(), AuthorityUtils.createAuthorityList(user.getRole())); } } ``` 在上述代码,如果用户被锁定,则会抛出LockedException异常,从而阻止用户登录
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值