使用带有SecurityMockMvcRequestPostProcessors.user
的Spring会话时,是否可以使用HeaderHttpSessionStrategy
为测试用户提供支持。
我尝试过类似的事情:
mockMvc.perform(
get(URL)
.with(user("user").password("pwd").roles("USER", "ADMIN")))
.andExpect(status().isOk())
但它返回403。
如果没有with(user(
,我会获得401,因此存在差异。
我有一个简单的SecurityConfig
包含:
http
.anonymous()
.and()
.authorizeRequests()
.antMatchers("/api/**").hasAuthority("USER")
.and()
.csrf()
.disable()
.httpBasic()
.and()
.requestCache()
.requestCache(new NullRequestCache());
我和https://github.com/spring-projects/spring-session/tree/1.0.1.RELEASE/samples/rest非常相似,因为我有一个端点,我使用http basic进行身份验证。它通过标头返回身份验证令牌,然后在其他REST调用中使用。
所以我希望我能在这种情况下使用with(user(
来简化测试。
答案 0 :(得分:0)
是的,你应该能够做到这一点。问题是
.with(user("user").password("pwd").roles("USER", "ADMIN")))
正在应用角色,这意味着会自动添加ROLE_前缀。
相反,您的配置正在使用:
.antMatchers("/api/**").hasAuthority("USER")
不会自动添加ROLE_前缀。相反,请尝试使用:
.antMatchers("/api/**").hasRole("USER")
注意:我还更新了测试以包含example of with(user("user"))。