我已经配置了一个独立的mockMvc和一个相应的xml安全配置,用于测试我的控制器,该控制器使用@PreAuthorize(hasAnyRole('DM,CD'))进行注释。但是我的测试结果总是达到200,即使我与角色不正确的用户打电话。我相信我的xml配置错过了一些东西,但这只是一个假设。
这是我要测试的控制器:
@RestController
@RequestMapping(value = "/v1/view")
@PreAuthorize("hasAnyRole('Data Manager,Content Designer')")
public class ViewController {
ObjectMapper objectMapper = new JSONMapper();
@Autowired
ViewApiService viewApiService;
//Constructor is needed for tests
ViewController(ViewApiService viewApiService) {
this.viewApiService = viewApiService;
}
public ViewController() {
}
@TruncateLogData
@RequestMapping(method = RequestMethod.GET)
public List<View> getViewItems() throws GenericEngineException {
return viewApiService.getViews();
}
}
这是从主配置中借用的测试spring-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<!-- ****** START Spring Security Configuration *******-->
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<constructor-arg>
<list>
<security:filter-chain pattern="/**" filters="
httpSessionContextIntegrationFilter,
logoutFilter,
basicAuthenticationProcessingFilter,
basicExceptionTranslationFilter,
servletApiBridge,
filterSecurityInterceptor"/>
</list>
</constructor-arg>
</bean>
<!-- ****** START Spring Filters *******-->
<!-- Session integration filter -->
<bean id="httpSessionContextIntegrationFilter"
class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
<constructor-arg>
<bean class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
<property name='allowSessionCreation' value='false'/>
</bean>
</constructor-arg>
</bean>
<!-- Basic Authentication processing filter -->
<bean id="basicAuthenticationProcessingFilter" class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
<constructor-arg ref="authenticationManager"/>
<constructor-arg ref="basicAuthenticationEntryPoint"/>
</bean>
<bean id="basicAuthenticationEntryPoint" class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint">
<property name="realmName" value="restapi"/>
</bean>
<!-- Basic Exception translation filter -->
<bean id="basicExceptionTranslationFilter" class="org.springframework.security.web.access.ExceptionTranslationFilter">
<constructor-arg ref="basicAuthenticationEntryPoint"/>
</bean>
<!-- Security Context Holder Aware Request filter
Filter that passes wrapped HttpServletRequest which overrides getUserPrincipal() to return current Authentication
-->
<bean id="servletApiBridge" class="org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter"/>
<!-- Logout filter
Filter that logs the user out in SpringSecurity
-->
<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg value="/" index="0"/>
<constructor-arg index="1">
<bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</constructor-arg>
</bean>
<!-- ****** END Spring Filters *******-->
<!-- ****** START Spring Security interceptor config *******-->
<!--Define authentication manager, decision manager and secure URL patterns -->
<bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="accessDecisionManager"/>
<property name="securityMetadataSource">
<security:filter-security-metadata-source>
<security:intercept-url pattern="/api/**" access="ROLE_ADMIN"/>
</security:filter-security-metadata-source>
</property>
</bean>
<!-- ****** END Spring Security interceptor config *******-->
<!-- ****** START Spring authentication config *******-->
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<constructor-arg>
<list>
<ref bean="usernamePasswordAuthenticationProvider"/>
</list>
</constructor-arg>
</bean>
<!-- Custom UsernamePassword Authentication Provider -->
<bean id="usernamePasswordAuthenticationProvider" class="com.custom.UsernamePasswordAuthenticationProvider">
<property name="adminLogin" value="true"/>
<property name="customLoginFacade" ref="userSessionFactoryFacade"/>
<property name="additionalRole" value="ROLE_ADMIN"/>
<property name="userInterfaceType" value="API"/>
</bean>
<!-- ****** END Spring authentication config *******-->
<!-- ****** START Spring authorization config *******-->
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
<constructor-arg>
<list>
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>
</list>
</constructor-arg>
</bean>
<!-- ****** END Spring authorization config *******-->
<!-- ****** END Spring Security Configuration *******-->
<bean id="userSessionFactoryFacade" class="com.custom.CustomLoginFacadeImpl"/>
</beans>
这是我对控制器的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/testContextConfig.xml", "/spring-security.xml"})
@WebAppConfiguration
public class ViewControllerTest {
private MockMvc mockMvc;
private List<View> viewList;
@Mock
private ViewApiService viewApiService;
@Autowired
private Filter springSecurityFilterChain;
@Before
public void setup() throws JSONException {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(new ViewController(viewApiService))
.addFilter(springSecurityFilterChain)
.setHandlerExceptionResolvers(TestServletExceptionHandler.exceptionResolver())
.build();
viewList = new ArrayList<>();
//initialization of resource to get
viewList.add(new View("1", "view1", content1));
}
@Test
@WithMockUser(username = "testUser3", roles = {"DM"})
public void testIncorrectAccessToControllersMethods() throws Exception {
when(viewApiService.getViews()).thenReturn(viewList);
mockMvc.perform(get("/v1/view"))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
verify(viewApiService, times(1)).getViews();
}
@Test
@WithMockUser(username = "testUser4", roles = {"OTHER_ROLE"})
public void testDMAccessToControllersMethods() throws Exception {
when(viewApiService.getViews()).thenReturn(viewList);
mockMvc.perform(get("/v1/view"))
.andExpect(status().isUnauthorized());
verify(viewApiService, times(0)).getViews();
}
但结果我得到了
ViewControllerTest.testIncorrectAccessToControllersMethods Status expected:<401> but was:<200>
testContextConfig.xml文件只是一个空的上下文。
任何建议将不胜感激
更新 创建带有相应注释的ViewControllerInterface并没有帮助,也没有添加
<global-method-security pre-post-annotations="enabled" />
配置文件
更新2
有趣的是,当我尝试使用mockMvc.perform(get("/v1/view").with(user("name"))).andReturn().getResponse()
我收到了
NoSuchMethodError: javax.servlet.http.HttpServletRequest.getServletContext()Ljavax/servlet/ServletContext;
at org.springframework.security.test.web.support.WebTestUtils.findFilter(WebTestUtils.java:120)
所以看起来我的securityFilterChain没有应用于请求(但是,在调试中我可以看到mockMvc实例中的所有过滤器)
答案 0 :(得分:0)
经过几个小时的挖掘,这是为什么:
手动实例化MockMvcBuilders.standaloneSetup
获取ViewController
(不使用Spring实例化,因此不使用AOP实例化)。因此,不会拦截PreAuthorize,并且跳过安全检查。因此,您可以通过@Autowire控制器并将其传递给MockMvcBuilders.standaloneSetup
来模拟使用@MockBean
的服务,以使ViewApiService
的每个实例都被替换为模拟对象。