我正在Spring 4
使用Spring Security 3.2
. 到目前为止,该应用程序运行良好。MockMVC
现在我正在使用和为所有 REST 服务编写测试用例RestAssured
。
我有一个简单的控制器
@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>
该应用程序按预期工作,但是我运行测试用例时弹簧安全过滤器没有执行'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'
。但是我来自测试用例的请求从未进入过滤器。
有人可以指导我如何让请求通过该过滤器。
谢谢。