From a5b97bb56947398b14266bfac24c568b2ad79806 Mon Sep 17 00:00:00 2001 From: Eleftheria Stein Date: Fri, 18 Sep 2020 10:50:20 +0200 Subject: [PATCH] Prevent NullPointerException when session ID changes The old session ID may not exist in the session registry if the user is not authenticated. Closes gh-9011 --- .../core/session/SessionRegistryImpl.java | 8 +++++--- .../session/SessionRegistryImplTests.java | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/org/springframework/security/core/session/SessionRegistryImpl.java b/core/src/main/java/org/springframework/security/core/session/SessionRegistryImpl.java index 73623f1bc4..34119b1d47 100644 --- a/core/src/main/java/org/springframework/security/core/session/SessionRegistryImpl.java +++ b/core/src/main/java/org/springframework/security/core/session/SessionRegistryImpl.java @@ -108,9 +108,11 @@ public class SessionRegistryImpl implements SessionRegistry, ApplicationListener else if (event instanceof SessionIdChangedEvent) { SessionIdChangedEvent sessionIdChangedEvent = (SessionIdChangedEvent) event; String oldSessionId = sessionIdChangedEvent.getOldSessionId(); - Object principal = this.sessionIds.get(oldSessionId).getPrincipal(); - removeSessionInformation(oldSessionId); - registerNewSession(sessionIdChangedEvent.getNewSessionId(), principal); + if (this.sessionIds.containsKey(oldSessionId)) { + Object principal = this.sessionIds.get(oldSessionId).getPrincipal(); + removeSessionInformation(oldSessionId); + registerNewSession(sessionIdChangedEvent.getNewSessionId(), principal); + } } } diff --git a/core/src/test/java/org/springframework/security/core/session/SessionRegistryImplTests.java b/core/src/test/java/org/springframework/security/core/session/SessionRegistryImplTests.java index df9ea8376d..14a9e847ee 100644 --- a/core/src/test/java/org/springframework/security/core/session/SessionRegistryImplTests.java +++ b/core/src/test/java/org/springframework/security/core/session/SessionRegistryImplTests.java @@ -173,6 +173,25 @@ public class SessionRegistryImplTests { assertThat(this.sessionRegistry.getAllSessions(principal, false)).isEmpty(); } + @Test + public void sessionIdChangedEventWhenSessionIdNotSavedThenDoesNothing() { + final String oldSessionId = "old-session-id"; + final String newSessionId = "new-session-id"; + this.sessionRegistry.onApplicationEvent(new SessionIdChangedEvent("") { + @Override + public String getOldSessionId() { + return oldSessionId; + } + + @Override + public String getNewSessionId() { + return newSessionId; + } + }); + assertThat(this.sessionRegistry.getSessionInformation(oldSessionId)).isNull(); + assertThat(this.sessionRegistry.getSessionInformation(newSessionId)).isNull(); + } + private boolean contains(String sessionId, Object principal) { List info = this.sessionRegistry.getAllSessions(principal, false); for (SessionInformation sessionInformation : info) {