前言
这篇文章咱们来分析一下org.springframework.boot.actuate.security,org.springframework.boot.actuate.audit中的代码,这2个包的类是对spring security 的事件进行处理的.类图以下:html
AuditEvent–> 1个值对象–>表明了1个audit event: 在特定的时间,1个特定的用户或者代理,实施了1个特定类型的动做.AuditEvent记录了有关AuditEvent的细节.web
其类上有以下注解:spring
@JsonInclude(Include.NON_EMPTY)
表明该类中为空(“”)或者为null的属性不会被序列化。数组
该类的字段以下:session
private final Date timestamp; // 资源 private final String principal; private final String type; private final Map<String, Object> data;
AuditApplicationEvent–> 封装AuditEvent.代码以下:app
public class AuditApplicationEvent extends ApplicationEvent { private final AuditEvent auditEvent; public AuditApplicationEvent(String principal, String type, Map<String, Object> data) { this(new AuditEvent(principal, type, data)); } AuditApplicationEvent(String principal, String type, String... data) { this(new AuditEvent(principal, type, data)); } public AuditApplicationEvent(Date timestamp, String principal, String type, Map<String, Object> data) { this(new AuditEvent(timestamp, principal, type, data)); } public AuditApplicationEvent(AuditEvent auditEvent) { super(auditEvent); Assert.notNull(auditEvent, "AuditEvent must not be null"); this.auditEvent = auditEvent; } public AuditEvent getAuditEvent() { return this.auditEvent; } }
AbstractAuditListener –>处理AuditApplicationEvent事件的抽象类.代码以下:ide
public abstract class AbstractAuditListener implements ApplicationListener<AuditApplicationEvent> { @Override public void onApplicationEvent(AuditApplicationEvent event) { onAuditEvent(event.getAuditEvent()); } protected abstract void onAuditEvent(AuditEvent event); }
AuditEventRepository–> 关于AuditEvent的dao实现.声明了以下4个方法:spring-boot
// 添加日志 void add(AuditEvent event); // 查询指定日期以后的AuditEvent List<AuditEvent> find(Date after); // 根据给定的Date和principal(资源)得到对应的AuditEvent List<AuditEvent> find(String principal, Date after); // 根据给的date,principal,type 类获取给定的AuditEvent List<AuditEvent> find(String principal, Date after, String type);
InMemoryAuditEventRepository –> AuditEventRepository接口的惟一实现.post
该类的字段以下:性能
// AuditEvent数组默认的默认大小 private static final int DEFAULT_CAPACITY = 4000; // 用于对events进行操做时 加的锁 private final Object monitor = new Object(); /** * Circular buffer of the event with tail pointing to the last element. * 循环数组 */ private AuditEvent[] events; // 最后1个元素的下标 private volatile int tail = -1;
构造器以下:
public InMemoryAuditEventRepository() { this(DEFAULT_CAPACITY); } public InMemoryAuditEventRepository(int capacity) { this.events = new AuditEvent[capacity]; }
AuditEventRepository中的方法实现以下:
@Override public void add(AuditEvent event) { Assert.notNull(event, "AuditEvent must not be null"); synchronized (this.monitor) { this.tail = (this.tail + 1) % this.events.length; this.events[this.tail] = event; } } @Override public List<AuditEvent> find(Date after) { return find(null, after, null); } @Override public List<AuditEvent> find(String principal, Date after) { return find(principal, after, null); } //上面两个方法最终调用这个方法 @Override public List<AuditEvent> find(String principal, Date after, String type) { LinkedList<AuditEvent> events = new LinkedList<AuditEvent>(); synchronized (this.monitor) { // 1. 遍历events for (int i = 0; i < this.events.length; i++) { // 1.1 得到最新的AuditEvent AuditEvent event = resolveTailEvent(i); // 1.2 若是AuditEvent 不等于null而且符合查询要求的话,就加入到events中 if (event != null && isMatch(principal, after, type, event)) { events.addFirst(event); } } } // 2. 返回结果集 return events; } //过滤不和条件的事件 private boolean isMatch(String principal, Date after, String type, AuditEvent event) { boolean match = true; match = match && (principal == null || event.getPrincipal().equals(principal)); match = match && (after == null || event.getTimestamp().compareTo(after) >= 0); match = match && (type == null || event.getType().equals(type)); return match; } //得到最新的AuditEvent private AuditEvent resolveTailEvent(int offset) { int index = ((this.tail + this.events.length - offset) % this.events.length); return this.events[index]; }
返回结果集
这里有2个问题:
一、前面说过访问events的时候都须要进行加锁,为何resolveTailEvent方法没有加锁?
缘由以下: resolveTailEvent的调用点只有1个,就是在find(String Date , String)中,而在该方法中已经加锁了,所以该方法不须要加锁.
二、resolveTailEvent方法加锁能够吗
答: 能够,缘由是synchronized 是可重入的.可是不推荐,若是加上,会产生性能损耗.
关于这个方法的实现原理咱们仍是举个例子比较好.假设咱们的数组长度为3个,此时已经放满数组了,以下:
[0,1,2]
此时tail = 2, 而后咱们继续放入3,则数组以下:
[3,1,2],此时tail = 0. 而后咱们调用find.在该方法中会调用resolveTailEvent.
第1次传入的是0,则index = (0+3-0)%3 = 0,得到的正是3.
第2次传入的是1,则index = (0+3-1)%3 = 2,得到的正是2.
第3次传入的是2,则index = (0+3-2)%3 = 1,得到的正是1.
所以说find(String, Date, String)得到的结果时按照添加的顺序倒序返回的.
自动装配:
声明在AuditAutoConfiguration类内的static AuditEventRepositoryConfiguration配置类中,代码以下:
@ConditionalOnMissingBean(AuditEventRepository.class) protected static class AuditEventRepositoryConfiguration { @Bean public InMemoryAuditEventRepository auditEventRepository() throws Exception { return new InMemoryAuditEventRepository(); } }
当beanFactory中不存在 AuditEventRepository类型的bean时生效.注册1个id为auditEventRepository,类型为InMemoryAuditEventRepository的bean.
AuditListener–> AbstractAuditListener的默认实现.监听AuditApplicationEvent事件而后存储到AuditEventRepository中. 代码以下:
public class AuditListener extends AbstractAuditListener { private static final Log logger = LogFactory.getLog(AuditListener.class); private final AuditEventRepository auditEventRepository; public AuditListener(AuditEventRepository auditEventRepository) { this.auditEventRepository = auditEventRepository; } @Override protected void onAuditEvent(AuditEvent event) { if (logger.isDebugEnabled()) { logger.debug(event); } this.auditEventRepository.add(event); } }
监听到AuditApplicationEvent时,直接将其封装的AuditEvent加入到AuditEventRepository中.仍是比较简单的.
自动装配以下:
在AuditAutoConfiguration中进行了声明,代码以下:
@Bean @ConditionalOnMissingBean(AbstractAuditListener.class) public AuditListener auditListener() throws Exception { return new AuditListener(this.auditEventRepository); }
@Bean–> 注册1个id为auditListener,类型为AuditListener的bean
@ConditionalOnMissingBean(AbstractAuditListener.class) –> 当beanFactory中不存在类型为AbstractAuditListener的bean时生效。
注意,在AuditListener中注入的是InMemoryAuditEventRepository
AbstractAuthenticationAuditListener–> 暴露 Spring Security AbstractAuthenticationEvent(认证事件) 将其转换为AuditEvent 的抽象ApplicationListener基类.
代码以下:
public abstract class AbstractAuthenticationAuditListener implements ApplicationListener<AbstractAuthenticationEvent>, ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { this.publisher = publisher; } protected ApplicationEventPublisher getPublisher() { return this.publisher; } protected void publish(AuditEvent event) { if (getPublisher() != null) { getPublisher().publishEvent(new AuditApplicationEvent(event)); } } }
AuthenticationAuditListener的默认实现
字段以下:
// 当发生AuthenticationSuccessEvent事件时添加到AuditEvent中的type public static final String AUTHENTICATION_SUCCESS = "AUTHENTICATION_SUCCESS"; // 当发生AbstractAuthenticationFailureEvent事件时添加到AuditEvent中的type public static final String AUTHENTICATION_FAILURE = "AUTHENTICATION_FAILURE"; // 当发生AuthenticationSwitchUserEvent事件时添加到AuditEvent中的type public static final String AUTHENTICATION_SWITCH = "AUTHENTICATION_SWITCH"; private static final String WEB_LISTENER_CHECK_CLASS = "org.springframework.security.web.authentication.switchuser.AuthenticationSwitchUserEvent"; private WebAuditListener webListener = maybeCreateWebListener(); // 只要加入spring-boot-starter-security的依赖,就会在当前类路径下存在org.springframework.security.web.authentication.switchuser.AuthenticationSwitchUserEvent // 所以会返回WebAuditListener private static WebAuditListener maybeCreateWebListener() { if (ClassUtils.isPresent(WEB_LISTENER_CHECK_CLASS, null)) { return new WebAuditListener(); } return null; }
onApplicationEvent 方法实现以下:
public void onApplicationEvent(AbstractAuthenticationEvent event) { // 1. 若是验证失败, if (event instanceof AbstractAuthenticationFailureEvent) { onAuthenticationFailureEvent((AbstractAuthenticationFailureEvent) event); } // 2.若是webListener不等于null.而且该事件为AuthenticationSwitchUserEvent else if (this.webListener != null && this.webListener.accepts(event)) { this.webListener.process(this, event); } // 3. 若是是AuthenticationSuccessEvent else if (event instanceof AuthenticationSuccessEvent) { onAuthenticationSuccessEvent((AuthenticationSuccessEvent) event); } }
一、若是验证失败(AbstractAuthenticationFailureEvent),则发送AuditEvent事件,其type为AUTHENTICATION_FAILURE.代码以下:
private void onAuthenticationFailureEvent(AbstractAuthenticationFailureEvent event) { Map<String, Object> data = new HashMap<String, Object>(); data.put("type", event.getException().getClass().getName()); data.put("message", event.getException().getMessage()); if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_FAILURE, data)); }
二、若是webListener不等于null.而且该事件为AuthenticationSwitchUserEvent,则发送AuditEvent事件,其type为AUTHENTICATION_SWITCH.代码以下:
public void process(AuthenticationAuditListener listener, AbstractAuthenticationEvent input) { if (listener != null) { AuthenticationSwitchUserEvent event = (AuthenticationSwitchUserEvent) input; Map<String, Object> data = new HashMap<String, Object>(); if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } data.put("target", event.getTargetUser().getUsername()); listener.publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_SWITCH, data)); } }
三、若是是AuthenticationSuccessEvent,则发送AuditEvent事件,其type为AUTHENTICATION_SUCCESS.代码以下:
private void onAuthenticationSuccessEvent(AuthenticationSuccessEvent event) { Map<String, Object> data = new HashMap<String, Object>(); if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } publish(new AuditEvent(event.getAuthentication().getName(), AUTHENTICATION_SUCCESS, data)); }
自动装配:
在AuditAutoConfiguration中进行了声明,代码以下:
@Bean @ConditionalOnClass(name = "org.springframework.security.authentication.event.AbstractAuthenticationEvent") @ConditionalOnMissingBean(AbstractAuthenticationAuditListener.class) public AuthenticationAuditListener authenticationAuditListener() throws Exception { return new AuthenticationAuditListener(); }
一、@Bean –> 注册1个id为authenticationAuditListener, AuthenticationAuditListener的bean
二、@ConditionalOnClass(name = “org.springframework.security.authentication.event.AbstractAuthenticationEvent”)–> 当在当前类路径下存在org.springframework.security.authentication.event.AbstractAuthenticationEvent时生效
三、@ConditionalOnMissingBean(AbstractAuthenticationAuditListener.class)–>beanFactory中不存在AbstractAuthenticationAuditListener类型的bean时生效.
AbstractAuthorizationAuditListener –>1个暴露AbstractAuthorizationEvent(受权事件)做为AuditEvent的抽象ApplicationListener基类.代码以下:
public abstract class AbstractAuthorizationAuditListener implements ApplicationListener<AbstractAuthorizationEvent>, ApplicationEventPublisherAware { private ApplicationEventPublisher publisher; @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { this.publisher = publisher; } protected ApplicationEventPublisher getPublisher() { return this.publisher; } protected void publish(AuditEvent event) { if (getPublisher() != null) { getPublisher().publishEvent(new AuditApplicationEvent(event)); } } }
AuthorizationAuditListener–> AbstractAuthorizationAuditListener的默认实现
字段以下:
// 发生AuthorizationFailureEvent事件时对应的AuditEvent的类型 public static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";
onApplicationEvent代码以下:
public void onApplicationEvent(AbstractAuthorizationEvent event) { // 1. 若是是AuthenticationCredentialsNotFoundEvent事件,则发送AuditEvent事件,type为AUTHENTICATION_FAILURE if (event instanceof AuthenticationCredentialsNotFoundEvent) { onAuthenticationCredentialsNotFoundEvent( (AuthenticationCredentialsNotFoundEvent) event); } // 2. 若是是AuthorizationFailureEvent事件,则发送AuditEvent事件,type为AUTHORIZATION_FAILURE else if (event instanceof AuthorizationFailureEvent) { onAuthorizationFailureEvent((AuthorizationFailureEvent) event); } }
一、若是是AuthenticationCredentialsNotFoundEvent事件,则发送AuditEvent事件,type为AUTHENTICATION_FAILURE.代码以下:
private void onAuthenticationCredentialsNotFoundEvent( AuthenticationCredentialsNotFoundEvent event) { Map<String, Object> data = new HashMap<String, Object>(); data.put("type", event.getCredentialsNotFoundException().getClass().getName()); data.put("message", event.getCredentialsNotFoundException().getMessage()); publish(new AuditEvent("<unknown>", AuthenticationAuditListener.AUTHENTICATION_FAILURE, data)); }
二、若是是AuthorizationFailureEvent事件,则发送AuditEvent事件,type为AUTHORIZATION_FAILURE.代码以下:
private void onAuthorizationFailureEvent(AuthorizationFailureEvent event) { Map<String, Object> data = new HashMap<String, Object>(); data.put("type", event.getAccessDeniedException().getClass().getName()); data.put("message", event.getAccessDeniedException().getMessage()); if (event.getAuthentication().getDetails() != null) { data.put("details", event.getAuthentication().getDetails()); } publish(new AuditEvent(event.getAuthentication().getName(), AUTHORIZATION_FAILURE, data)); }
自动装配:
在AuditAutoConfiguration中进行了装配,代码以下:
@Bean @ConditionalOnClass(name = "org.springframework.security.access.event.AbstractAuthorizationEvent") @ConditionalOnMissingBean(AbstractAuthorizationAuditListener.class) public AuthorizationAuditListener authorizationAuditListener() throws Exception { return new AuthorizationAuditListener(); }
准备工做
若是想让 spring boot 应用激活AuditEvent的事件的处理,须要加入spring-boot-starter-security依赖,代码以下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
光加入依赖还不够,咱们须要加入security的配置,否则AuthorizationAuditListener,AuthenticationAuditListener 监听什么事件呢? 所以,咱们加入以下代码:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/error-log").hasAuthority("ROLE_TEST").antMatchers("/", "/home") .permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and() .logout().logoutUrl("/logout").permitAll().and().authorizeRequests(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
在configureGlobal中,咱们在内存中生成了1个用户:用户名为user,密码为password,角色为USER.
在configure中咱们配置了以下内容:
声明1个UserController,代码以下:
@Controller public class UserController { @RequestMapping("/") public String index() { return "index"; } @RequestMapping("/hello") public String hello() { return "hello"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "login"; } @RequestMapping("/error-test") public String error() { return "1"; } }
在src/main/resources/templates目录下建立以下几个页面:
hello.html,代码以下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
</form>
</body>
</html>
index.html,代码以下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security入门</title>
</head>
<body>
<h1>欢迎使用Spring Security!</h1>
<p>点击 <a th:href="@{/hello}">这里</a> 打个招呼吧</p>
</body>
</html>
login.html,代码以下:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security Example </title> </head> <body> <div th:if="${param.error}"> 用户名或密码错 </div> <div th:if="${param.logout}"> 您已注销成功 </div> <form th:action="@{/login}" method="post"> <div><label> 用户名 : <input type="text" name="username"/> </label></div> <div><label> 密 码 : <input type="password" name="password"/> </label></div> <div><input type="submit" value="登陆"/></div> </form> </body> </html>
测试
启动应用后咱们访问以下连接: http://127.0.0.1:8080/,返回的是以下页面:
点击index.html 中的超连接后,因为须要进行验证,返回到login页面,如图:
此时咱们输入错误的用户名,密码,返回的页面以下:
此时咱们输入user,password 后,返回的页面以下:
点击注销后,页面以下:
此时咱们访问 http://127.0.0.1:8080/error-test,因为没有登陆,仍是调回到登陆页面.
访问 http://127.0.0.1:8080/auditevents,返回的结果以下:
{ events: [ { timestamp: "2018-01-23T03:52:13+0000", principal: "anonymousUser", type: "AUTHORIZATION_FAILURE", data: { details: { remoteAddress: "127.0.0.1", sessionId: null }, type: "org.springframework.security.access.AccessDeniedException", message: "Access is denied" } }, { timestamp: "2018-01-23T03:54:21+0000", principal: "aaa", type: "AUTHENTICATION_FAILURE", data: { details: { remoteAddress: "127.0.0.1", sessionId: "DFDB023AEEF41BBD8079EC32402CBFD8" }, type: "org.springframework.security.authentication.BadCredentialsException", message: "Bad credentials" } }, { timestamp: "2018-01-23T03:55:50+0000", principal: "user", type: "AUTHENTICATION_SUCCESS", data: { details: { remoteAddress: "127.0.0.1", sessionId: "DFDB023AEEF41BBD8079EC32402CBFD8" } } }, { timestamp: "2018-01-23T03:58:38+0000", principal: "anonymousUser", type: "AUTHORIZATION_FAILURE", data: { details: { remoteAddress: "127.0.0.1", sessionId: "6E6E614D638B6F5EE5B7E8CF516E2534" }, type: "org.springframework.security.access.AccessDeniedException", message: "Access is denied" } }, { timestamp: "2018-01-23T04:00:01+0000", principal: "anonymousUser", type: "AUTHORIZATION_FAILURE", data: { details: { remoteAddress: "127.0.0.1", sessionId: "6E6E614D638B6F5EE5B7E8CF516E2534" }, type: "org.springframework.security.access.AccessDeniedException", message: "Access is denied" } }, { timestamp: "2018-01-23T04:00:12+0000", principal: "user", type: "AUTHENTICATION_SUCCESS", data: { details: { remoteAddress: "127.0.0.1", sessionId: "6E6E614D638B6F5EE5B7E8CF516E2534" } } } ] }
解析
zhuan:https://blog.csdn.net/qq_26000415/article/details/79138270