【发布时间】:2019-11-10 02:37:49
【问题描述】:
这是我的设置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/signup", "/health").permitAll()
.anyRequest().authenticated().and()
.formLogin()
.loginPage("/login")
.permitAll()
...
测试类:
@ExtendWith(SpringExtension.class)
@WebMvcTest
@WithMockUser
class ApiControllerTest {
...
@WithMockUser 可以正常使用以下 GET:
mockMvc.perform(get("/api/book/{id}", id))
.andExpect(status().isOk())
...
但不使用 POST:
mockMvc.perform(post("/api/book")
.contentType(MediaType.APPLICATION_JSON)
.content(payload))
.andExpect(status().isCreated())
...
当我查看 MockHttpServletResponse 的日志时,我注意到响应正在重定向到登录页面,如下所示:
MockHttpServletResponse:
Status = 302
Error message = null
Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY", Location:"/login"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = /login
Cookies = []
我知道@WithMockUser 为模拟用户身份验证提供了大量默认值。为什么它不适用于有状态的 API 请求?
【问题讨论】:
标签: spring-boot spring-mvc spring-security