Class TestSecurityContextHolder
- java.lang.Object
-
- org.springframework.security.test.context.TestSecurityContextHolder
-
public final class TestSecurityContextHolder extends java.lang.Object
TheTestSecurityContextHolder
is very similar toSecurityContextHolder
, but is necessary for testing. For example, we cannot populate the desiredSecurityContext
inSecurityContextHolder
for web based testing. In a web request, theSecurityContextPersistenceFilter
will override theSecurityContextHolder
with the value returned by theSecurityContextRepository
. At the end of theFilterChain
theSecurityContextPersistenceFilter
will clear out theSecurityContextHolder
. This means if we make multiple web requests, we will not know whichSecurityContext
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
- Before a test is executed, the
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static void
clearContext()
static SecurityContext
getContext()
Gets theSecurityContext
fromTestSecurityContextHolder
.static void
setAuthentication(Authentication authentication)
Creates a newSecurityContext
with the givenAuthentication
.static void
setContext(SecurityContext context)
-
-
-
Method Detail
-
clearContext
public static void clearContext()
-
getContext
public static SecurityContext getContext()
Gets theSecurityContext
fromTestSecurityContextHolder
.- Returns:
- the
SecurityContext
fromTestSecurityContextHolder
.
-
setContext
public static void setContext(SecurityContext context)
- Parameters:
context
- theSecurityContext
to use
-
setAuthentication
public static void setAuthentication(Authentication authentication)
Creates a newSecurityContext
with the givenAuthentication
. TheSecurityContext
is set onTestSecurityContextHolder
andSecurityContextHolder
.- Parameters:
authentication
- theAuthentication
to use- Since:
- 5.1.1
-
-