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
This commit is contained in:
Andy Wilkinson 2019-02-12 16:21:53 +00:00
parent a74717307f
commit 8e6b4629d4
2 changed files with 15 additions and 3 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -103,7 +103,9 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList
if (event.getAuthentication().getDetails() != null) { if (event.getAuthentication().getDetails() != null) {
data.put("details", event.getAuthentication().getDetails()); data.put("details", event.getAuthentication().getDetails());
} }
data.put("target", event.getTargetUser().getUsername()); if (event.getTargetUser() != null) {
data.put("target", event.getTargetUser().getUsername());
}
listener.publish(new AuditEvent(event.getAuthentication().getName(), listener.publish(new AuditEvent(event.getAuthentication().getName(),
AUTHENTICATION_SWITCH, data)); AUTHENTICATION_SWITCH, data));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2018 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -92,6 +92,16 @@ public class AuthenticationAuditListenerTests {
.isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH); .isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH);
} }
@Test
public void testAuthenticationSwitchBackToAnonymous() {
AuditApplicationEvent event = handleAuthenticationEvent(
new AuthenticationSwitchUserEvent(
new UsernamePasswordAuthenticationToken("user", "password"),
null));
assertThat(event.getAuditEvent().getType())
.isEqualTo(AuthenticationAuditListener.AUTHENTICATION_SWITCH);
}
@Test @Test
public void testDetailsAreIncludedInAuditEvent() { public void testDetailsAreIncludedInAuditEvent() {
Object details = new Object(); Object details = new Object();