Browse Source

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
Eleftheria Stein 5 years ago
parent
commit
a5b97bb569

+ 5 - 3
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);
+			}
 		}
 	}
 

+ 19 - 0
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<SessionInformation> info = this.sessionRegistry.getAllSessions(principal, false);
 		for (SessionInformation sessionInformation : info) {