0

I recently inherited some java code, that needs to switch to stateless in HttpSecurity configuration:

http.csrf().disable()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

After that, some tests using MockMvc failed. I know @WithMockUser will not work with stateless, so what should I change to get it pass? Here is an example test:

    @Before
    public void setUp() throws Exception {

        this.mockMvc = MockMvcBuilders.standaloneSetup(apAdminController)
            .apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
            .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
            .build();

        storeUser = new StoreUser();
        storeUser.setUsername("smith");
        storeUser.setEnabled(true);
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    public void testViewStoreUserWithAdmin() {
        try {
            mockMvc.perform(
                get("{resource}/1", RESOURCE).with(testSecurityContext()))
                .andDo(print())
                .andExpect(status().isOk());

        } catch (Exception e) {
            fail("Test failed: " + e.getMessage());
        }
    }
Annie C
  • 764
  • 2
  • 12
  • 31

1 Answers1

0

It took me a long time to find answers, here is what I ended up with, in case anyone is struggling:

After changing SessionCreationPolicy from 'If_REQUIRED' or 'ALWAYS' to 'STATELESS' on the tests: replace import .SecurityMockMvcRequestPostProcessors.testSecurityContext; to import .SecurityMockMvcRequestPostProcessors.user;

and use this in the setup:

this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
            .addFilters(springSecurityFilterChain)
            .build();

Remove all the annotation @WithMockUser and finally, change

get("{resource}", RESOURCE).with(testSecurityContext()))

to get("{resource}", RESOURCE).with(user("admin").roles("ADMIN")))

Annie C
  • 764
  • 2
  • 12
  • 31