Skip to content

Support empty cotext ReactorContextTestExecutionListener pass Security #12115

Open
@bakomchik

Description

@bakomchik

I would like to have option to pass SecurityContextHolder.createEmptyContext() into my reactor test

Expected Behavior
Test passed

@ExtendWith(SpringExtension::class)
@TestExecutionListeners(
    WithSecurityContextTestExecutionListener::class,
    ReactorContextTestExecutionListener::class
)
internal class SpringSecurityIdentityProviderTest {
    @Test
    @WithEmptySecurityContext
    fun `when security context is empty then context should be passed to test`() {
        Mono.defer {
            ReactiveSecurityContextHolder.getContext()
                .onEmptyError { IllegalStateException("Require security context") }
                .filter { it.authentication == null }
        }.onEmptyError { IllegalStateException("Require security context with Empty auth") }
            .block()
    }
}



class EmptySecurityContextFactory : WithSecurityContextFactory<WithEmptySecurityContext> {
    override fun createSecurityContext(annotation: WithEmptySecurityContext?): SecurityContext {
        return SecurityContextHolder.createEmptyContext()
    }

}
@WithSecurityContext(factory = EmptySecurityContextFactory::class)
annotation class WithEmptySecurityContext

Current Behavior

test failed

Context

Sometime we receive empty SecurityContext in our logic and would like to have option to test these cases.
But ReactorContextTestExecutionListener do not pass empty SecurityContext to tests.
Workaround is to modify stream context like this:

   Mono.defer {
            ReactiveSecurityContextHolder.getContext()
                .onEmptyError { IllegalStateException("Require security context") }
                .filter { it.authentication == null }
        }.onEmptyError { IllegalStateException("Require security context with Empty auth") }
            .contextWrite({
                val withSecurityContext = ReactiveSecurityContextHolder.withSecurityContext(
                    Mono.just(SecurityContextHolder.createEmptyContext())
                )
                withSecurityContext.putAll(it.readOnly())
                withSecurityContext
            })
            .block()

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions