Class TestSecurityContextHolder


  • public final class TestSecurityContextHolder
    extends java.lang.Object
    The TestSecurityContextHolder is very similar to SecurityContextHolder, but is necessary for testing. For example, we cannot populate the desired SecurityContext in SecurityContextHolder for web based testing. In a web request, the SecurityContextPersistenceFilter will override the SecurityContextHolder with the value returned by the SecurityContextRepository. At the end of the FilterChain the SecurityContextPersistenceFilter will clear out the SecurityContextHolder. This means if we make multiple web requests, we will not know which SecurityContext to use on subsequent requests. Typical usage is as follows:
    Since:
    4.0
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void clearContext()
      Clears the SecurityContext from TestSecurityContextHolder and SecurityContextHolder.
      static org.springframework.security.core.context.SecurityContext getContext()
      Gets the SecurityContext from TestSecurityContextHolder.
      static void setAuthentication​(org.springframework.security.core.Authentication authentication)
      Creates a new SecurityContext with the given Authentication.
      static void setContext​(org.springframework.security.core.context.SecurityContext context)
      Sets the SecurityContext on TestSecurityContextHolder and SecurityContextHolder.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • clearContext

        public static void clearContext()
        Clears the SecurityContext from TestSecurityContextHolder and SecurityContextHolder.
      • setContext

        public static void setContext​(org.springframework.security.core.context.SecurityContext context)
        Sets the SecurityContext on TestSecurityContextHolder and SecurityContextHolder.
        Parameters:
        context - the SecurityContext to use
      • setAuthentication

        public static void setAuthentication​(org.springframework.security.core.Authentication authentication)
        Creates a new SecurityContext with the given Authentication. The SecurityContext is set on TestSecurityContextHolder and SecurityContextHolder.
        Parameters:
        authentication - the Authentication to use
        Since:
        5.1.1