Spring Security OAuth2 用户登录失败事件发布及监听

Spring事件简介

Spring中的事件分为三部分:事件、监听器、事件源,其中事件是核心,涉及到ApplicationEventPublisher接口、ApplicationEvent类、ApplicationListener接口

定义用户登录失败事件

1
2
3
4
5
6
7
8
9
10
/**
* @Description: 定义用户登录失败事件
* @Package: UserLoginFailedEvent
* @Version: 1.0
*/
public class UserLoginFailedEvent extends ApplicationEvent {
public UserLoginFailedEvent(Authentication authentication) {
super(authentication);
}
}

定义事件监听器

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @Description: 用户登录失败监听器
* @Package: cn.appblog.security.oauth2.event.listener.UserLoginFailedListener
* @Version: 1.0
*/
@Component
public class UserLoginFailedListener implements ApplicationListener<UserLoginFailedEvent> {
@Override
public void onApplicationEvent(UserLoginFailedEvent event) {
System.out.println("用户验证信息: failure");
}
}

事件发布

定义ApplicationEventPublisher对象并发布事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* @Description: 用户自定义身份认证
* @Package: cn.appblog.security.oauth2.provider.UserAuthenticationProvider
* @Version: 1.0
*/
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserAuthDetailsService authUserDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private ApplicationEventPublisher publisher;

/**
* 认证处理,返回一个Authentication的实现类则代表认证成功,返回null则代表认证失败
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
if (StringUtils.isBlank(username)) {
throw new UsernameNotFoundException("username用户名不可以为空");
}
if (StringUtils.isBlank(password)) {
throw new BadCredentialsException("密码不可以为空");
}
//获取用户信息
UserDetails user = authUserDetailsService.loadUserByUsername(username);
//比较前端传入的密码明文和数据库中加密的密码是否相等
if (!passwordEncoder.matches(password, user.getPassword())) {
//发布密码不正确事件
publisher.publishEvent(new UserLoginFailedEvent(authentication));
throw new BadCredentialsException("password密码不正确");
}
//获取用户权限信息
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}

/**
* 如果该AuthenticationProvider支持传入的Authentication对象,则返回true
*/
@Override
public boolean supports(Class<?> aClass) {
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}

通过以上操作就可以在用户登录失败后有效的监听到失败状态,并且很好的解耦代码

本文转载参考 原文 并加以调试

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :