Skip to content

Test using @WithMockUser fails with 401 UNAUTHORIZED with 3.2 #14207

Closed
@andrashatvani

Description

@andrashatvani

Describe the bug
The following test works with 3.1, but fails with 401 UNAUTHORIZED with 3.2:

To Reproduce

@SpringBootTest(
    webEnvironment = RANDOM_PORT,
    classes = [Application::class],
    properties = ["spring.main.allow-bean-definition-overriding=true"]
)
@TestConstructor(autowireMode = ALL)
@WithMockUser(authorities = [ROLE_USER])
class HandlerIntegrationTest(
    @MockkBean
    private val searcher: Searcher,
    private val client: WebTestClient,
) {
    @Test
    fun search() {
        val searchResponse = SearchResponse(
            result = listOf(),
            page = 1,
            pageSize = 20,
            total = 0,
            filterOptions = FilterOptions(setOf(), setOf()),
            sort = setOf(),
            descending = listOf(false),
        )
        coEvery { searcher.search(any()) } returns searchResponse
        client.get()
            .uri { it.path("$ENDPOINT/search").build() }
            .exchange()
            .expectStatus()
            .isOk
            .expectBody<SearchResponse>()
            .consumeWith {
                assertThat(it.responseBody).isEqualTo(searchResponse)
            }
    }
}

A custom MapReactiveUserDetailsService has been in place and it looks like this:

    @Bean
    @ConditionalOnProperty(value = ["spring.security.user.passwordGenerated"], matchIfMissing = true, havingValue = "false")
    fun userDetailsService(): MapReactiveUserDetailsService {
        val actuatorUser = User
            .withUsername(securityProperties.user.name)
            .password("{noop}${securityProperties.user.password}")
            .authorities(AUTHORITY_ACTUATOR, AUTHORITY_ACCESS_MONITORING, AUTHORITY_ACCESS_INTERNAL_API).build()

        val monitoringUser = User
            .withUsername(monitoringProperties.username)
            .password("{noop}${monitoringProperties.password}")
            .authorities(AUTHORITY_ACCESS_MONITORING)
            .build()

        return MapReactiveUserDetailsService(actuatorUser, monitoringUser)
    }

Expected behavior
The test works

Sample
Currently we have tried in 3 different projects with different services always with this same result, thus this might not be an isolated case, but rather a major issue, thus hopefully you can easily identify the cause.

Metadata

Metadata

Labels

in: testAn issue in spring-security-testtype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions