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
-
Method Summary
Modifier and TypeMethodDescriptionstatic voidstatic SecurityContextGets theSecurityContextfromTestSecurityContextHolder.static voidsetAuthentication(Authentication authentication) Creates a newSecurityContextwith the givenAuthentication.static voidsetContext(SecurityContext context)
-
Method Details
-
clearContext
public static void clearContext() -
getContext
Gets theSecurityContextfromTestSecurityContextHolder.- Returns:
- the
SecurityContextfromTestSecurityContextHolder.
-
setContext
- Parameters:
context- theSecurityContextto use
-
setAuthentication
Creates a newSecurityContextwith the givenAuthentication. TheSecurityContextis set onTestSecurityContextHolderandSecurityContextHolder.- Parameters:
authentication- theAuthenticationto use- Since:
- 5.1.1
-