public final class TestSecurityContextHolder extends Object
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:
TestSecurityContextHolder
is
populated. Typically this is done using the
WithSecurityContextTestExcecutionListener
MockMvc
it is typically used with
SecurityMockMvcRequestPostProcessors.testSecurityContext()
. Which ensures
the SecurityContext
from TestSecurityContextHolder
is
properly populated.TestSecurityContextHolder
and the
SecurityContextHolder
are cleared outModifier and Type | Method and Description |
---|---|
static void |
clearContext()
|
static SecurityContext |
getContext()
Gets the
SecurityContext from TestSecurityContextHolder . |
static void |
setContext(SecurityContext context)
|
public static void clearContext()
public static SecurityContext getContext()
SecurityContext
from TestSecurityContextHolder
.SecurityContext
from TestSecurityContextHolder
.public static void setContext(SecurityContext context)
context
- the SecurityContext
to use