Class ListeningSecurityContextHolderStrategy

  • All Implemented Interfaces:
    SecurityContextHolderStrategy

    public final class ListeningSecurityContextHolderStrategy
    extends java.lang.Object
    implements SecurityContextHolderStrategy
    An API for notifying when the SecurityContext changes. Note that this does not notify when the underlying authentication changes. To get notified about authentication changes, ensure that you are using setContext(org.springframework.security.core.context.SecurityContext) when changing the authentication like so:
            SecurityContext context = SecurityContextHolder.createEmptyContext();
            context.setAuthentication(authentication);
            SecurityContextHolder.setContext(context);
     
    To add a listener to the existing SecurityContextHolder, you can do:
      SecurityContextHolderStrategy original = SecurityContextHolder.getContextHolderStrategy();
      SecurityContextChangedListener listener = new YourListener();
      SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(original, listener);
      SecurityContextHolder.setContextHolderStrategy(strategy);
     
    NOTE: Any object that you supply to the SecurityContextHolder is now part of the static context and as such will not get garbage collected. To remove the reference, reset the strategy like so:
       SecurityContextHolder.setContextHolderStrategy(original);
     
    This will then allow YourListener and its members to be garbage collected.
    Since:
    5.6