Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Principal in Session when using Spring-Session

We have extended the principal with our own User object. This way the object is available with every request. When a user updates his information, the principal needs to updated with this new data. When not using spring-session, this method works. However, with spring-session, it does not.

I checked in the spring-session code, and the RedisOperationsSessionRepository:save(RedisSession session) only calls session.saveDelta(), which only saves changed attributes. So, how do we update a principal in session?

Note - the place where the principal is updated is in the service layer, so we do not have access to a SessionAuthenticationStrategy.

like image 667
nsdiv Avatar asked Jun 19 '26 15:06

nsdiv


1 Answers

Found a way to do this, so answering my own question. Spring-security stores the context as an attribute in HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY. So updating the key manually (instead of through Spring-Session) results in the Principal being updated.

httpSession.setAttribute(
  HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
  SecurityContextHolder.getContext()
);
like image 88
nsdiv Avatar answered Jun 24 '26 06:06

nsdiv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!