With deprecation of the `SecurityContextRepository.loadContext(HttpRequestResponseHolder)` method, how do we add `Set-Cookie` to the response?

Viewed 94

Context

We have for some time been using Spring-Security to protect our edge Spring-Boot Java applications.

Our system-wide authentication architecture (which is used by Spring-Boot apps, other Java apps and NodeJS apps) makes use of client-side session cookies (i.e. those that die when a browser window is closed) which store a session ID, and a cluster-internal session store keyed on those IDs.

Implementation in Spring-Boot 2.6.x and below

For our Spring-Boot applications, we have a long-standing custom implementation of SecurityContextRepository where the implementation of the SecurityContext loadContext(HttpRequestResponseHolder) method performs something along the lines of the following:

  1. If there is no session ID cookie, return an empty SecurityContext.
  2. If there is a session ID cookie, which corresponds to a valid session, return a valid security context and, in some circumstances, add a Set-Cookie directive on the response to update the cookie.
  3. If there is a session ID cookie, which does not correspond to a valid session, return an empty SecurityContext, and add a Set-Cookie directive on the response to clear the invalid cookie.

Proposed implementation in Spring-Boot 2.7.x and above

Making the upgrade from Spring-Boot 2.6.x to 2.7.x, the SecurityContext loadContext(HttpRequestResponseHolder) method has been deprecated. I've been looking at the alternative advised, namely Supplier<SecurityContext> loadContext(HttpServletRequest), and wondering how to keep our system behaviour constant while migrating to the new APIs. Referring to my numbering above, I have come to the conclusion so far that:

  1. No change required - the response was never used
  2. If we need to update the cookie on the response, then ensure that the relevant information is available in the SecurityContext that we return, and then customise the saveContext() implementation to ensure the cookie is updated if necessary
  3. Return an empty SecurityContext as before, and customise the saveContext() implementation to ensure the cookie is cleared in if the security context is empty.

The question(s)

I'd be grateful if one of the Spring team, or another enlightened StackOverflow user, would be able to confirm that the above migration strategy is appropriate, or correct me if I have misunderstood anything.

If I have got it right, perhaps it would be worth updating the Javadoc of the deprecated method to make it clearer for other users also?

Many thanks.

0 Answers
Related