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