Unit Testing /login in Spring MVC using MockMvc

2020-03-12 02:48发布

问题:

I have a very simple REST application created using Spring MVC. (Code is available at GitHub.) It has a simple WebSecurityConfigurer as follows:

@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);
}

When I run the application, both the custom controllers and the login/logout pages work without a problem. I can even unit test /user/new via MockMvc. However, when I try to test /login with the following function

@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"));
}

it fails as follows:

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>

But I am pretty user POST to /login is working when I run the application instead of test. Further, when I try make a GET or HEAD request (as suggested in the Headers = {Allow=[HEAD, GET]} line of the logs), this time I receive a 404. Any ideas about what is going on and how can I fix it?

回答1:

I noticed the github link now. I believe you need to configure security filter also for your tests. Something like

 mockMvc = MockMvcBuilders.webApplicationContextSetup(webApplicationContext)
                .addFilter(springSecurityFilterChain)
                .build();

Some additional settings might be necessary, you might check http://www.petrikainulainen.net/programming/spring-framework/integration-testing-of-spring-mvc-applications-security/ for inspiration.



回答2:

You could use spring security testing classes to test form based login. You need to do the following to test form based login.

Maven dependency:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <version>4.0.0.M1</version>
    <scope>test</scope>
</dependency>

<repositories>
    <repository>
        <id>spring-snasphot</id>
        <url>https://repo.spring.io/libs-snapshot</url>
    </repository>
</repositories>

Test class:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;

RequestBuilder requestBuilder = formLogin().user("username").password("passowrd");
mockMvc.perform(requestBuilder)
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(cookie().exists("JSESSIONID"));


回答3:

Following my post here: Spring MockMvcBuilders Security filter

I have manage to create REST API with UsernamePasswordAuthenticationToken for /oauth/token but I didn't manage to create the test for my protected resource (on running server it work fine). Could you show us your REST interface ?



回答4:

Testing SpringSession, I achieved to get the session cookie and saving session to an embedded Redis doing this:

@Autowired
private SessionRepositoryFilter<?> springSessionRepositoryFilter;
...

@Before
public void setup() {
    mvc = MockMvcBuilders
        .webAppContextSetup(context)
        .addFilters(springSessionRepositoryFilter)
        .apply(springSecurity())
        .build();
}

Hope it helps.