diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java index 328ef924160..971a67a2bf0 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java @@ -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"); * 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) { 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(), AUTHENTICATION_SWITCH, data)); } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java index 58bffa8baf8..39cdcd9a304 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/security/AuthenticationAuditListenerTests.java @@ -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"); * you may not use this file except in compliance with the License. @@ -92,6 +92,16 @@ public class AuthenticationAuditListenerTests { .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 public void testDetailsAreIncludedInAuditEvent() { Object details = new Object();