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
TestSecurityContextHolder
is populated. Typically this is done using theWithSecurityContextTestExecutionListener
- The test is ran. When used with
MockMvc
it is typically used withSecurityMockMvcRequestPostProcessors.testSecurityContext()
. Which ensures theSecurityContext
fromTestSecurityContextHolder
is properly populated. - After the test is executed, the
TestSecurityContextHolder
and theSecurityContextHolder
are cleared out
- Since:
- 4.0
-
Method Summary
Modifier and TypeMethodDescriptionstatic void
static SecurityContext
Gets theSecurityContext
fromTestSecurityContextHolder
.static void
setAuthentication
(Authentication authentication) Creates a newSecurityContext
with the givenAuthentication
.static void
setContext
(SecurityContext context)
-
Method Details
-
clearContext
public static void clearContext() -
getContext
Gets theSecurityContext
fromTestSecurityContextHolder
.- Returns:
- the
SecurityContext
fromTestSecurityContextHolder
.
-
setContext
- Parameters:
context
- theSecurityContext
to use
-
setAuthentication
Creates a newSecurityContext
with the givenAuthentication
. TheSecurityContext
is set onTestSecurityContextHolder
andSecurityContextHolder
.- Parameters:
authentication
- theAuthentication
to use- Since:
- 5.1.1
-