Skip to content

Commit d2c01e5

Browse files
vaadin-botknoobiemcollovati
authored
fix: allow access to SecurityContext for invalidated http session (#23004) (#23017)
Co-authored-by: Knoobie <Knoobie@gmx.de> Co-authored-by: Marco Collovati <marco@vaadin.com>
1 parent cbc0d95 commit d2c01e5

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinAwareSecurityContextHolderStrategy.java

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,17 @@ private Optional<SecurityContext> getFromVaadinSession() {
6969
if (session == null || session.getSession() == null) {
7070
return Optional.empty();
7171
}
72-
Object securityContext = session.getSession().getAttribute(
73-
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
74-
if (securityContext instanceof SecurityContext) {
75-
return Optional.of((SecurityContext) securityContext);
76-
} else {
72+
try {
73+
Object securityContext = session.getSession().getAttribute(
74+
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
75+
if (securityContext instanceof SecurityContext context) {
76+
return Optional.of(context);
77+
} else {
78+
return Optional.empty();
79+
}
80+
} catch (IllegalStateException ignored) {
81+
// Session throws IllegalStateException when accessing
82+
// attributes of an invalid session
7783
return Optional.empty();
7884
}
7985
}

vaadin-spring/src/test/java/com/vaadin/flow/spring/security/VaadinAwareSecurityContextHolderStrategyTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,22 @@ public void explicitUsedWhenNoSessionAvailable() {
8181
Assert.assertEquals(explicit,
8282
vaadinAwareSecurityContextHolderStrategy.getContext());
8383
}
84+
85+
@Test
86+
public void getContext_invalidateSession_getsThreadSecurityContext() {
87+
SecurityContext explicit = Mockito.mock(SecurityContext.class);
88+
vaadinAwareSecurityContextHolderStrategy.setContext(explicit);
89+
90+
VaadinSession vaadinSession = Mockito.mock(VaadinSession.class);
91+
HttpSession httpSession = Mockito.mock(HttpSession.class);
92+
Mockito.when(vaadinSession.getSession())
93+
.thenReturn(new WrappedHttpSession(httpSession));
94+
Mockito.doThrow(IllegalStateException.class).when(httpSession)
95+
.getAttribute(
96+
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
97+
VaadinSession.setCurrent(vaadinSession);
98+
99+
Assert.assertEquals(explicit,
100+
vaadinAwareSecurityContextHolderStrategy.getContext());
101+
}
84102
}

0 commit comments

Comments
 (0)