Announcement Announcement Module
No announcement yet.
Can I get Spring Security to just store the username in the HttpSession? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Can I get Spring Security to just store the username in the HttpSession?

    I'm trying to use replicated sessions in a database, which means I want to keep session data small (always a good idea anyway of course) and it has to be serializable. I'm using Spring Security, which puts the "principal" and the granted authorities in the session. Sometimes my UserDetails object has 3rd party data attached, and it's not serializable. What I'd like to do, at a very high level is:

    - store only the username in the HttpSession between requests. This will get serialized to the database as part of the session replication mechanism.
    - at the start of a request, "resolve" that username into the matching UserDetails, making use of a caching layer so I won't hit the database to load the user
    - for the duration of the request, Spring Security accesses the UserDetails object just like normal. This may mean that it has to live in the session temporarily.
    - just before the end of the request, remove the UserDetails and put the username back in.

    If anyone has suggestions for how to do this, or reasons why it won't work, or other ways to achieve the same goal, I would be glad to read them.

  • #2
    I think the best answer would be to change your object to be serializable. You are quite unlikely to gain much be removing the data from session and obtaining it from a datastore even if there is a cache involved (after all cache is just another type of serialization). As for the third party data you can write your own beans to hold it so it can be serializable.

    If you really wanted to go with this approach you could write a custom implementation of SecurityContextRepository. You can refer to HttpSessionSecurityContextRepository, the default implementation, for an example of how to implement it. You can then use the security-context-repository-ref attribute to configure your custom implementation to be used.


    • #3
      The idea is to minimize the amount of data that gets replicated as part of the session. In my system, most of the time, a single app server will handle a given session throughout the lifetime of that session. Session replication is in place primarily for seamless failover and for "zero downtime" deployments. For a single app server, it doesn't really matter if data is stored in the session or in a cache on that app server. I just want to minimize the load on the shared resource (database) that handles centralized session storage, to allow better scaling.

      OK thanks for the pointer to where to get started if I want to implement something like this. I was hoping it would be something already implemented that I could configure, but that was wishful thinking.