Class TestSecurityContextHolder
- java.lang.Object
-
- org.springframework.security.test.context.TestSecurityContextHolder
-
public final class TestSecurityContextHolder extends java.lang.ObjectTheTestSecurityContextHolderis very similar toSecurityContextHolder, but is necessary for testing. For example, we cannot populate the desiredSecurityContextinSecurityContextHolderfor web based testing. In a web request, theSecurityContextPersistenceFilterwill override theSecurityContextHolderwith the value returned by theSecurityContextRepository. At the end of theFilterChaintheSecurityContextPersistenceFilterwill clear out theSecurityContextHolder. This means if we make multiple web requests, we will not know whichSecurityContextto use on subsequent requests. Typical usage is as follows:- Before a test is executed, the
TestSecurityContextHolderis populated. Typically this is done using theWithSecurityContextTestExecutionListener - The test is ran. When used with
MockMvcit is typically used withSecurityMockMvcRequestPostProcessors.testSecurityContext(). Which ensures theSecurityContextfromTestSecurityContextHolderis properly populated. - After the test is executed, the
TestSecurityContextHolderand theSecurityContextHolderare 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 voidclearContext()static SecurityContextgetContext()Gets theSecurityContextfromTestSecurityContextHolder.static voidsetAuthentication(Authentication authentication)Creates a newSecurityContextwith the givenAuthentication.static voidsetContext(SecurityContext context)
-
-
-
Method Detail
-
clearContext
public static void clearContext()
-
getContext
public static SecurityContext getContext()
Gets theSecurityContextfromTestSecurityContextHolder.- Returns:
- the
SecurityContextfromTestSecurityContextHolder.
-
setContext
public static void setContext(SecurityContext context)
- Parameters:
context- theSecurityContextto use
-
setAuthentication
public static void setAuthentication(Authentication authentication)
Creates a newSecurityContextwith the givenAuthentication. TheSecurityContextis set onTestSecurityContextHolderandSecurityContextHolder.- Parameters:
authentication- theAuthenticationto use- Since:
- 5.1.1
-
-