我有一个Spring MVC + Spring Security Web应用程序。 该应用程序在配置中设置了自定义会话身份验证策略
http.sessionManagement()
.sessionAuthenticationStrategy( ... )
由于该策略包含复杂的逻辑,因此必须通过集成测试来测试其行为。
当我们使用spring-security-test @WithMockUser时,控制器方法在测试中被调用,但是我们的身份验证策略为未调用。
在Spring Security测试中强制执行完整身份验证过程以确保确实调用了会话身份验证策略的正确方法是什么?
或者换个说法:如何调用整个spring安全过滤器链?
感谢创意。
答案 0 :(得分:1)
在集成测试中,提供一个static WebSecurityConfigurerAdapter
,它将被拿起。
例如:
@EnableWebSecurity
static class CustomSessionAuthenticationStrategyConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionAuthenticationStrategy(customSessionAuthenticationStrategy);
}
}
更新:
这是Spring Security 4.x中的MockMvc测试。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class SessionAuthenticationStrategyTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
public void requestWhenCustomSessionAuthenticationStrategyProvidedThenCalled() throws Exception {
this.mvc.perform(formLogin().user("user").password("password"));
verify(CustomSessionAuthenticationStrategyConfig.customSessionAuthenticationStrategy)
.onAuthentication(any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@EnableWebSecurity
static class CustomSessionAuthenticationStrategyConfig extends WebSecurityConfigurerAdapter {
static SessionAuthenticationStrategy customSessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
@Override
public void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.sessionManagement()
.sessionAuthenticationStrategy(customSessionAuthenticationStrategy);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").authorities("ROLE_USER");
}
}
}