Class TestSecurityContextHolder
- java.lang.Object
-
- org.springframework.security.test.context.TestSecurityContextHolder
-
public final class TestSecurityContextHolder extends 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
- Author:
- Rob Winch
- Before a test is executed, the
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static void
clearContext()
static org.springframework.security.core.context.SecurityContext
getContext()
Gets theSecurityContext
fromTestSecurityContextHolder
.static void
setContext(org.springframework.security.core.context.SecurityContext context)
-
-
-
Method Detail
-
clearContext
public static void clearContext()
-
getContext
public static org.springframework.security.core.context.SecurityContext getContext()
Gets theSecurityContext
fromTestSecurityContextHolder
.- Returns:
- the
SecurityContext
fromTestSecurityContextHolder
.
-
setContext
public static void setContext(org.springframework.security.core.context.SecurityContext context)
- Parameters:
context
- theSecurityContext
to use
-
-