Wednesday, February 6, 2013

Spring SecurityContextHolder and SecurityContextHolderStrategy

SecurityContextHolder

This is the place where we store the SecurityContext for the current execution thread.
SecurityContext is stored according to a given strategy.
This is a convenient class. i.e. Has only static methods.
This class has manily following methods.

  • void clearContext()
  • void setContext(SecurityContext context)
  • SecurityContext getContext()


SecurityContextHolderStrategy

This is an interface which has the same main methods as SecurityContextHolder.
i.e.
  • void clearContext()
  • void setContext(SecurityContext context)
  • SecurityContext getContext()

Implementations of SecurityContextHolderStrategy determines how to store the SecurityContext against a thread.
Spring comes with 3 implementations of SecurityContextHolderStrategy.
  • ThreadLocalSecurityContextHolderStrategy
  • GlobalSecurityContextHolderStrategy
  • InheritableThreadLocalSecurityContextHolderStrategy

ThreadLocalSecurityContextHolderStrategy
This class maintains a ThreadLocal of SecurityContext
static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<SecurityContext>()
  • getContext() - gets the  SecurityContext from the ThreadLocal
  • setContext() - puts the SecurityContext into the ThreadLocal.