Request body is empty when no authentication is present for secure APIs

714 Views Asked by At

I am trying to log the request body on all requests in a spring boot reactive application secured with spring security. But I am running into an issue where the request body is logged only if the basic auth header is present (even if the username and password are invalid). But if no auth header is present the request body does not get logged. I am unsure what I am missing and would like to find out how I maybe able to get access to the request body for cases where there is no authentication header present.

The request body logging is done using an authentication entry point set on HttpBasicSpec. The security configuration looks as follows:

@Configuration
@EnableWebFluxSecurity
class SecurityConfiguration {

    private val logger = LoggerFactory.getLogger(this::class.java)

    @Bean
    fun securityConfigurationBean(http: ServerHttpSecurity) =
        http.csrf().disable()
                .cors().disable()
                .httpBasic()
                .authenticationEntryPoint { exchange, _ ->
                    exchange.request.body
                            .subscribe { logger.info(CharsetUtil.UTF_8.decode(it.asByteBuffer()).toString()) }
                            .let { Mono.error(HttpServerErrorException(HttpStatus.UNAUTHORIZED)) }
                }.and().authorizeExchange().anyExchange().authenticated().and().build()
}

There is a test router config that has a one route:

@Configuration
class TestRouterConfig {

    @Bean
    fun testRoutes() =
            router {
                POST("/test") {
                    ServerResponse.ok().bodyValue("This is a test route")
                }
            }
}

When I make a request to http:localhost:8080/test with a request body of

{"sample": "sample"}

with an invalid username and password in the basic auth header, I see the following in the console:

2019-12-06 11:51:18.175  INFO 11406 --- [ctor-http-nio-2] uration$$EnhancerBySpringCGLIB$$5b5f0067 : {"sample": "sample"}

But when I remove authentication all together I don't see the above logging statement for the same endpoint (I am using a rest client to make these calls).

The versions of tools/frameworks/languages:

  • Kotlin: 1.3.50
  • Spring boot: 2.2.1
  • Java: 12
  • Gradle: 5.6.4
  • Spring dependency management: 1.0.8.RELEASE

I would like to be able to log the request body for all requests that result in an authentication failure including the absence of an authentication header and would appreciate any help in this regard. My apologies if this has been discussed/posted elsewhere.

Thank you!

0

There are 0 best solutions below