Spring MVC testing (security Integration test), JSESSIONID is not present

雨燕双飞 提交于 2020-01-02 02:38:29

问题


I have created custom login form for my spring boot app. In my form integration test, I want to check that received cookies contain JSESSIONID and XSRF-TOKEN.

But, I received only XSRF-TOKEN.

Here is my test:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class UserIT {

    @Autowired
    private WebApplicationContext context;
    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    @Value("${local.server.port}")
    private Integer port;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc =
                MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain)
                        .build();
    }

    @Test
    public void getUserInfoTest() throws Exception {
        disableSslVerification();

        MvcResult result =
                mockMvc.perform(formLogin("/login").user("roy").password("spring")).andExpect(authenticated())
                        .andReturn();
        Cookie sessionId = result.getResponse().getCookie("JSESSIONID");
        Cookie token = result.getResponse().getCookie("XSRF-TOKEN");
}

Security conf:

@Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off   
        http
            //.httpBasic()
            //.and()
                .headers().frameOptions().disable()
            .and()
                .antMatcher("/**").authorizeRequests()
                .antMatchers("/actuator/health").permitAll()
                .antMatchers("/actuator/**").hasAuthority(Authority.Type.ROLE_ADMIN.getName())
                .antMatchers("/login**", "/index.html", "/home.html").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin().loginPage("/login.jsp")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginProcessingUrl("/login")
                     .permitAll()
            .and()
                .logout().logoutSuccessUrl("/login.jsp").permitAll()
            .and()
                .csrf().csrfTokenRepository(csrfTokenRepository())
            .and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
        // @formatter:on
    }

Please, help me to obtain the required result.


回答1:


You also don't see Set-Cookie header. For me it's a big limitation of MockMVC. For a workaround see Why does Spring MockMvc result not contain a cookie?.



来源:https://stackoverflow.com/questions/36600817/spring-mvc-testing-security-integration-test-jsessionid-is-not-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!