我有一个使用 Spring MVC 创建的非常简单的 REST 应用程序。 (代码可在GitHub.)它有一个简单的WebSecurityConfigurer如下:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/user/new").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.and()
.logout()
.permitAll()
.logoutSuccessHandler(logoutSuccessHandler);
}
当我运行该应用程序时,自定义控制器和登录/注销页面都可以正常工作。我什至可以单元测试 /user/new
via MockMvc
。但是,当我尝试测试时/login
具有以下功能
@Test
public void testUserLogin() throws Exception {
RequestBuilder requestBuilder = post("/login")
.param("username", testUser.getUsername())
.param("password", testUser.getPassword());
mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isOk())
.andExpect(cookie().exists("JSESSIONID"));
}
它失败如下:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /login
Parameters = {username=[test-user-UserControllerTest], password=[test-user-UserControllerTest-password]}
Headers = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpRequestMethodNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 405
Error message = Request method 'POST' not supported
Headers = {Allow=[HEAD, GET]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<200> but was:<405>
但我是相当用户POST
to /login
当我运行应用程序而不是测试时正在工作。此外,当我尝试制作一个GET
or HEAD
请求(如建议的Headers = {Allow=[HEAD, GET]}
日志行),这次我收到 404。关于发生了什么以及如何修复它有什么想法吗?