Home > OS >  How to test annotation based role-specific security in test annotated with `@WebMvcTest` and `@WithM
How to test annotation based role-specific security in test annotated with `@WebMvcTest` and `@WithM

Time:02-14

My Problem is that I can not test the role-based authentication of my annotated Rest Endpoints in my tests. The specified roles seem to make no difference

I am using annotation based security configuration on my REST-controllers like this:

@RestController
@RequestMapping("rest/person")
class PersonRestController(
    private val securityService: SecurityService,
    private val personService: PersonService,
) {

    @GetMapping("/list")
    @Secured(UserRole.Role.ROLE_COMPANY)
    fun list(): List<Person> {
        val companyId = securityService.currentUser.companyId
        return personService.findByCompany(companyId)
    }

}

In my Web Layer tests I am using @WebMvcTest with a shared config class, that provides all required beans (we have some shared ExceptionHandlers and Interceptors that I would like to test with my Controllers)

My Test looks like this:

@WebMvcTest(PersonRestController::class)
@Import(RestControllerTestConfig::class)
class GroupedScheduleRestControllerTest {

    @Autowired
    private lateinit var mvc: MockMvc

    @MockBean
    private lateinit var personService: PersonService

    // This bean is provided by RestControllerTestConfig
    @Autowired
    private lateinit var someSharedService: SomeSharedService


    @Test
    @WithMockUser(value = "[email protected]")
    fun testReturnsEmptyList() {
        val response = mvc.perform(MockMvcRequestBuilders.get("/rest/person/list"))

        response.andExpect(status().isOk)
            .andExpect(jsonPath("$.length()").value(0))
    }
}

Now I would like to add a unit test, that verifies, that only a user with the role COMPANY can access this endpoint - but I can't get this to work. My test always runs through when I add WithMockUser, independent of what I pass in for the roles. And it always fails with a 401 Unauthorized when I remove WithMockUser so some security setup seems to be happening but the @Secured in my RestEndpoint seems to have no effect.

Am I missing some configuration here to notify @WebMvcTest to pick up the Security annotations from the instantiated RestController?

CodePudding user response:

Okay in order for the @Secured annotations to be picked up, I added @EnableGlobalMethodSecurity(securedEnabled = true) to my Configuration class and it worked like a charm

  • Related