@AuthenticationPrincipal is always null when testing Spring Security

Viewed 146

I'm writing a test for my view controller and use MockMVC. Every method in controller uses @AuthenticationPrincipal annotation for getting the user. I tried to mock user with @WithMockUser() and with SecurityMockMvcRequestPocessors. And it works fine, as authorization passes. But the user, that is supposed to be set with AuthenticationPrincipal is always null. I really could find any solution to this problem. Here's the test

@WebMvcTest
public class GazerControllerTest {

@MockBean
UserService userService;
@MockBean
ClientService clientService;

@Autowired
MockMvc mockMvc;


@Test
@WithMockUser()
public void test() throws Exception {
    this.mockMvc.perform(get("/account")).andDo(print());
}

}

Controller

@GetMapping("/account")
public String getAccountPage(Model model, @AuthenticationPrincipal User user) {
    System.out.println(user); // null
    model.addAttribute("user", user);
    return "account";
}

Help me, please.

0 Answers
Related