0

I write tests for controllers and when I write a test for a POST handpoint, I get a 403 error returned, the reason for which is: o.s.security.web.csrf.CsrfFilter: Invalid CSRF token found

In my WebSecurityConfig CSRFs are disabled:

http.httpBasic(withDefaults())
                .sessionManagement(c -> c
                        .sessionCreationPolicy(STATELESS))
                .csrf(c -> c
                        .disable())
                .headers(c -> c
                        .frameOptions()
                        .disable());

But for some reason they are not disabled in tests. What should I do to get around this?

My AuthControllerTest class:

@AutoConfigureWebMvc
@AutoConfigureMockMvc(addFilters = false)
@WebMvcTest(controllers = AuthController.class)
public class AuthControllerTest {

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private Filter springSecurityFilterChain;

    //    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private TalentService talentService;

    @MockBean
    private AuthService authService;

    @MockBean
    private SponsorService sponsorService;

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

    @Test
    @Disabled
    public void givenLogin_whenValidUrlAndMethodAndUserCredentials_thenReturns200AndLoginResponse() throws Exception {
        String email = "test@mail.com";
        String password = "123456";
        LoginResponse expectedResponseBody = LoginResponse.builder()
                .id(1L)
                .token("token")
                .name("Name")
                .surname("Surname")
                .avatar("avatar")
                .build();

        Authentication authentication = new UsernamePasswordAuthenticationToken(email, password,
                Collections.singleton(new SimpleGrantedAuthority("TALENT")));
        Mockito.when(authService.login(authentication)).thenReturn(expectedResponseBody);
        mockMvc.perform(post("/login").with(httpBasic(email, password))).andDo(print()).andExpect(status().isOk()).andDo(print());
    }

    @Test
    @WithAnonymousUser
    public void givenMyProfile_whenUserIsNotAuthenticated_thenReturns401() throws Exception {
        mockMvc.perform(get("/auth/me")).andExpect(status().isUnauthorized()).andExpect(unauthenticated()).andDo(print());
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    public void givenMyProfile_whenUserIsAuthenticated_thenReturns200() throws Exception {
        AdminProfile expectedResponseBody = AdminProfile.builder()
                .id(1L)
                .role("ADMIN")
                .name("Admin")
                .surname("Adminchenko")
                .build();

        Mockito.when(authService.myProfile(Mockito.any(Authentication.class))).thenReturn(expectedResponseBody);
        mockMvc.perform(get("/auth/me")).andExpect(status().isOk()).andDo(print());
    }

    @Test
    public void givenTalentRegister_whenValidUrlAndContentType_thenReturns200() throws Exception {
        CreateTalent createTalent = new CreateTalent("test@mail.com", "123456",
                "Name", "Surname", "Java Developer");

        mockMvc.perform(post("/talents/register")
                        .content(objectMapper.writeValueAsString(createTalent))
                        .characterEncoding("utf-8")
                        .contentType("application/json")).andDo(print())
                .andExpect(status().isOk()).andDo(print());
    }
}
Mark
  • 3
  • 3
  • Does this answer your question? https://stackoverflow.com/questions/21749781/why-i-received-an-error-403-with-mockmvc-and-junit – Feel free May 25 '23 at 15:52
  • Yes, but it's not working for me. I still getting error Invalid CSRF token. Finally I want to disabled this. – Mark May 25 '23 at 18:14
  • Did you try to pass null here -> .addFilters((Filter) null)? – Feel free May 25 '23 at 20:50

0 Answers0