1

I have an UserRepository annotated with @PreAuthorize("hasRole('ROLE_ADMIN')"). When I perform a mockMvc request, the mocked authentication works as expected. But the repository access afterwards fails with:

 An Authentication object was not found in the SecurityContext

Here is my failing test:

@WithMockUser(roles = "ADMIN")
def "access repo with security"() {
    expect:
        mockMvc.perform(get("/"))
        employeeRepository.deleteAll()
        employeeRepository.count() == 0
}

This test (without mockMvc) succeeds:

@WithMockUser(roles = "ADMIN")
def "access repo with security"() {
    expect:
        employeeRepository.deleteAll()
        employeeRepository.count() == 0
}

Can anyone explain me, why it fails after mockMvc?

Jannik Weichert
  • 1,623
  • 16
  • 28

0 Answers0