Class TestSecurityContextHolder
java.lang.Object
org.springframework.security.test.context.TestSecurityContextHolder
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:
 - Before a test is executed, the TestSecurityContextHolderis populated. Typically this is done using theWithSecurityContextTestExecutionListener
- The test is ran. When used with MockMvcit is typically used withSecurityMockMvcRequestPostProcessors.testSecurityContext(). Which ensures theSecurityContextfromTestSecurityContextHolderis properly populated.
- After the test is executed, the TestSecurityContextHolderand theSecurityContextHolderare cleared out
- Since:
- 4.0
- Author:
- Rob Winch
- 
Method SummaryModifier and TypeMethodDescriptionstatic voidstatic org.springframework.security.core.context.SecurityContextGets theSecurityContextfromTestSecurityContextHolder.static voidsetContext(org.springframework.security.core.context.SecurityContext context) 
- 
Method Details- 
clearContextpublic static void clearContext()
- 
getContextpublic static org.springframework.security.core.context.SecurityContext getContext()Gets theSecurityContextfromTestSecurityContextHolder.- Returns:
- the SecurityContextfromTestSecurityContextHolder.
 
- 
setContextpublic static void setContext(org.springframework.security.core.context.SecurityContext context) - Parameters:
- context- the- SecurityContextto use
 
 
-