public final class TestSecurityContextHolder
extends java.lang.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
WithSecurityContextTestExecutionListener
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 |
setAuthentication(Authentication authentication)
Creates a new
SecurityContext with the given Authentication . |
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 usepublic static void setAuthentication(Authentication authentication)
SecurityContext
with the given Authentication
.
The SecurityContext
is set on TestSecurityContextHolder
and
SecurityContextHolder
.authentication
- the Authentication
to use