SpringSecurity密码错误5次锁定用户

第一步:创建 AuthenticationSuccessEventListener.java 用来处理登录成功的事件。

import com.mlog.sd.data.dao.UserDao;
import com.mlog.sd.data.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 登陆成功监听
 *
 */
@Component
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

	@Autowired
	private UserDao userDao;

	@Override
	public void onApplicationEvent(AuthenticationSuccessEvent authenticationSuccessEvent) {
		UserDetails userDetails = (UserDetails) authenticationSuccessEvent.getAuthentication().getPrincipal();
		String username = userDetails.getUsername();
		User newUser = new User();
		newUser.setActive(true);
		newUser.setUsername(username);
		newUser.setFailsCount(0);
		userDao.updateUser(username, newUser);
	}
}

第二步:新建AuthenticationFailureListener.java 用来处理登录失败的事件。

import com.mlog.sd.data.dao.UserDao;
import com.mlog.sd.data.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

/**
 * 登陆失败监听
 *
 */
@Component
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

	@Autowired
	private UserDao userDao;

	@Override
	public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent) {
		String username = authenticationFailureBadCredentialsEvent.getAuthentication().getPrincipal().toString();
		User user = userDao.findUser(username);
		if (user != null) {
			// 用户失败次数
			Integer fails = user.getFailsCount();
			if(fails==null){
				fails = 0;
			}
			fails++;
			// 超出失败5次,停用账户
			if (fails >= 5) {
				User newUser = new User();
				newUser.setActive(false);
				newUser.setUsername(username);
				newUser.setFailsCount(fails);
				userDao.updateUser(username, newUser);
			} else {
				User newUser = new User();
				newUser.setFailsCount(fails);
				newUser.setUsername(username);
				userDao.updateUser(username, newUser);
			}
		}
	}
}
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值