spring-security icon indicating copy to clipboard operation
spring-security copied to clipboard

SecurityContextRepository does not save security context into JDBC session if one of authentication field was changed

Open 0lgakuzmenko opened this issue 1 month ago • 0 comments

Description: When customized Authentication with some additional fields is used along with spring-session-jdbc and implicit session saving, then if one of the field of that Authentication was updated, SecurityContext is not persisted into JDBC session unless Authentication is explicitly re-set at SecurityContext.

Spring Boot ver. 3.5.8 Spring Security ver. 6.5.7 Spring Session ver. 3.5.3

Steps to Reproduce Use attached sample. It contains of CustomizedAuthenticationManager that performs authentication and wraps it with WrappedAuthentication. WrappedAuthentication contains extra data field. SecurityConfig sets sessions to be implicitly saved by Spring. IndexController contains 2 endpoints: /index that writes out current authentication details and /extra that updates extra data field in current authetication then writes it out.

  1. Run sample, log in (user/password) and then open /index endpoint. You'll see following data: Image

  2. Go to /extra endpoint, data has changed: Image

  3. Open /index endpoint again. It is expected that extraAuthData is ExtraAuthData{stringA='STRING C', stringB='STRING D'}, but actual value is still ExtraAuthData{stringA='String A', stringB='String B'} -- because session was loaded, but was not saved at step 2.

Stop the sample, go to org/session/test/sample/auth/WrappedAuthentication.java and uncomment line 69:

SecurityContextHolder.getContext().setAuthentication(shallowCopy()); // this force Spring Session to save updated authentication

Repeat steps 1-3 and this time at step 3 extraAuthData is ExtraAuthData{stringA='STRING C', stringB='STRING D'} as expected.

Expected behavior When authentication details are updated, changes are saved to JDBC session without setting Authentication object in SecurityContext.

Sample Attached session_demo.zip

0lgakuzmenko avatar Dec 04 '25 20:12 0lgakuzmenko