8

我为我的 Spring Boot 应用程序创建了自定义登录表单。在我的表单集成测试中,我想检查收到的 cookie 是否包含JSESSIONIDXSRF-TOKEN

但是,我只收到XSRF-TOKEN

这是我的测试:

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

安全配置:

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

请帮助我获得所需的结果。

4

2 回答 2

3

您也看不到 Set-Cookie 标头。对我来说,这是 MockMVC 的一大局限。有关解决方法,请参阅为什么 Spring MockMvc 结果不包含 cookie?.

于 2016-04-20T12:35:37.787 回答
0

如果您使用带有默认登录端点的 Spring Security,那么有一个好消息。调用 /login ep 后,您不需要来自 cookie 的 JSESSION。只需在您的测试方法上方使用@WithMockUser,执行登录请求,从现在开始,您的所有请求都将被授权为最后登录的用户。

于 2021-10-16T13:56:00.220 回答