Skip to content

Commit 8e6b462

Browse files
committed
Tolerate AuthenticationSwitchUserEvent with null target user
When Spring Security is misconfigured it's possible to switch from an anonymous user to a normal user. When switching back again, the corresponding AuthenticationSwitchUserEvent will have a null target user. Previously, Actuator's AuthenticationAuditListener would throw a NullPointerException when it received such an event. This commit updates the audit listener to defensively handled events with a null target user. Closes gh-15767
1 parent a747173 commit 8e6b462

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2017 the original author or authors.
2+
* Copyright 2012-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -103,7 +103,9 @@ public void process(AuthenticationAuditListener listener,
103103
if (event.getAuthentication().getDetails() != null) {
104104
data.put("details", event.getAuthentication().getDetails());
105105
}
106-
data.put("target", event.getTargetUser().getUsername());
106+
if (event.getTargetUser() != null) {
107+
data.put("target", event.getTargetUser().getUsername());
108+
}
107109
listener.publish(new AuditEvent(event.getAuthentication().getName(),
108110
AUTHENTICATION_SWITCH, data));
109111
}

spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2018 the original author or authors.
2+
* Copyright 2012-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -92,6 +92,16 @@ public void testAuthenticationSwitch() {
9292
.isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH);
9393
}
9494

95+
@Test
96+
public void testAuthenticationSwitchBackToAnonymous() {
97+
AuditApplicationEvent event = handleAuthenticationEvent(
98+
new AuthenticationSwitchUserEvent(
99+
new UsernamePasswordAuthenticationToken("user", "password"),
100+
null));
101+
assertThat(event.getAuditEvent().getType())
102+
.isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH);
103+
}
104+
95105
@Test
96106
public void testDetailsAreIncludedInAuditEvent() {
97107
Object details = new Object();

0 commit comments

Comments
 (0)