我正在使用Spring 4
Spring Security 3.2
。到目前为止,应用程序运行良好。现在,我正在使用MockMVC
和RestAssured
为所有REST服务编写测试用例。
我有一个简单的控制器
@RestController
@RequestMapping("/secure")
public class MyController{
@RequestMapping(method = RequestMethod.GET)
public String getAllMedia(){
return "SECURE TEST COMPLETE";
}
}
我的spring-rest-servlet.xml
文件有<mvc:annotation-driven />
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<mvc:annotation-driven />
<context:component-scan base-package="com.mp.web.controller.common" />
</beans>
spring-security-context.xml
看起来像这样
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<security:http create-session="stateless"
entry-point-ref="authenticationEntryPoint"
authentication-manager-ref="authenticationManager">
<security:custom-filter ref="customRestFilter"
position="BASIC_AUTH_FILTER" />
<security:intercept-url pattern="/api/p/**" access="ROLE_USER" />
<security:intercept-url pattern="/api/login**"
access="IS_AUTHENTICATED_ANONYMOUSLY" requires-channel="https" />
</security:http>
<bean id="authenticationEntryPoint"
class="com.mp.web.security.CustomAuthenticationEntryPoint" />
<bean id="customRestFilter"
class="com.mp.web.security.filter.AuthenticationTokenProcessingFilter">
<constructor-arg name="authenticationManager"
ref="authenticationManager" />
</bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="restAuthenticationProvider" />
</security:authentication-manager>
<bean id="restAuthenticationProvider"
class="com.mp.web.security.auth.RestAuthenticationProvider" />
</beans>
应用程序正在按预期工作,但是在运行测试用例时,spring安全过滤器未执行'customRestFilter'
这是我的测试类
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:application-context.xml",
"classpath:spring-rest-servlet.xml",
"classpath:spring-security-context.xml"})
public class Test {
@Autowired
private FilterChainProxy springSecurityFilterChain;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
MyController myController;
@Before
public void init(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter(springSecurityFilterChain).build();
}
@Test
public void test1() throws Exception {
given().mockMvc(mockMvc).standaloneSetup(myController)
.header("Authorization", userHeaderToken) // Token for user
.when().get("/secure")
.then().log().body();
}
}
userHeaderToken
用于标识我从哪个用户获得请求,以及'customRestFilter'
处理的所有用户。但我的测试用例请求从未进入过滤器。
有人可以指导我如何让请求通过该过滤器。
感谢。