0

When I enter the suspend function, the context is present. This function is called from a controller function that is also suspend.

suspend fun search(searchRequest: String): String? {
    val context = ReactiveSecurityContextHolder.getContext().map {
      it
    }.awaitFirstOrNull()
    log.info("The context here at the search is $context") 
    return someJava.something();
}

As soon as I get into java code the context is gone in java. If I call back into kotlin the security context is still gone.

public String something() {
  return someKotlin.something();
}

fun something(): String {
   val context = ReactiveSecurityContextHolder.getContext().map {
                    it
                 }.awaitFirstOrNull()
   log.info("The context here is always null. Why? $context") 
} 

Any idea how to resolve this issue?

Jesse Nelson
  • 776
  • 8
  • 21

2 Answers2

0

ReactiveSecurityContextHolder.getContext() is not supposed to be used like a global variable/storage.

You are suppose to get it once and perform all your operations on the result.

Related answer here https://stackoverflow.com/a/51350355/6167844

Dominic Fischer
  • 1,695
  • 10
  • 14
  • You should be able to access this context as many times as you need. It works perfectly fine as long as I don’t call java from Kotlin. I can access at any point while servicing the request. – Jesse Nelson Jun 22 '20 at 12:44
0

This issue occurred because on the java side there was some blocking code. As soon as you block, the publisher chain terminates and you lose the subscriber context. In hind site this is obvious. To resolve my issue, I passed the security context to the java method and just stored in a threadlocal object so it could be accessed later in the java code and passed back to kotlin when needed. It is somewhat ugly, but if you are unable to modify the java methods to return a publisher, this route is your only option

Jesse Nelson
  • 776
  • 8
  • 21