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
This commit is contained in:
Eleftheria Stein 2020-09-18 10:50:20 +02:00
parent 6e6d382357
commit a5b97bb569
2 changed files with 24 additions and 3 deletions

View File

@ -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);
}
}
}

View File

@ -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) {