//定义用户登录失败事件
public class UserLoginFailedEvent extends ApplicationEvent {
public UserLoginFailedEvent(Authentication authentication) {
super(authentication);
}
}
//用户登录失败监听器
@Slf4j
@Component
public class UserLoginFailedListener implements ApplicationListener<UserLoginFailedEvent> {
//错误了第四次返回true,然后锁定账号,第五次即使密码正确也会报账户锁定
Set<RequestLimitRule> rules = Collections.singleton(RequestLimitRule.of(1, TimeUnit.MINUTES, 3)); // 3 request per 1 minute, per key
RequestRateLimiter limiter = new InMemorySlidingWindowRequestRateLimiter(rules);
@Override
public void onApplicationEvent(UserLoginFailedEvent event) {
if (event.getSource() instanceof Authentication) {
Authentication authentication = (Authentication) event.getSource();
log.info(JSONObject.toJSONString(authentication));
boolean reachLimit = limiter.overLimitWhenIncremented(authentication.getName());
if (reachLimit) {
throw new LockedException("账户被锁定");
}
}
System.out.println("----用户验证信息---faile----------------------");
}
}
//用户自定义身份认证
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {
@Autowired
private MyUserDetailsService myUserDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private ApplicationEventPublisher publisher;
/**
* @Description 认证处理,返回一个Authentication的实现类则代表认证成功,返回null则代表认证失败
* @Date 2019/7/5 15:19
* @Version 1.0
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
if(StringUtils.isBlank(username)){
throw new OAuth2Exception("username用户名不可以为空");
}
if(StringUtils.isBlank(password)){
throw new OAuth2Exception("密码不可以为空");
}
//获取用户信息
UserDetails user = myUserDetailsService.loadUserByUsername(username);
//比较前端传入的密码明文和数据库中加密的密码是否相等
if (!passwordEncoder.matches(password, user.getPassword())) {
//发布密码不正确事件
publisher.publishEvent(new UserLoginFailedEvent(authentication));
throw new OAuth2Exception("用户名或者密码错误");
}
//获取用户权限信息
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
/**
* @Description 如果该AuthenticationProvider支持传入的Authentication对象,则返回true
* @Date 2019/7/5 15:18
* @Version 1.0
*/
@Override
public boolean supports(Class<?> aClass) {
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}
//限流依赖
<dependency>
<groupId>es.moki.ratelimitj</groupId>
<artifactId>ratelimitj-inmemory</artifactId>
<version>0.6.0</version>
</dependency>
spring cloud oauth2 登录一定次数后锁定
最新推荐文章于 2023-08-04 09:07:49 发布