第一步:创建 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);
}
}
}
}
版权声明:本文为jiangshuanshuan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。