Since you are using WebFlux, you are handling requests using event-loop.
You are not using thread-per-request model anymore, as with Tomcat.
Authentication is stored per context.
With Tomcat, when request arrives, Spring stores authentication in SecurityContextHolder
.
SecurityContextHolder
uses ThreadLocal
variable to store authentication. Specific authentication object is visible to you, only if you are trying to fetch it from ThreadLocal
object, in the same thread, in which it was set.
Thats why you could get authentication in controller via static call.
ThreadLocal object knows what to return to you, because it knows your context - your thread.
With WebFlux, you could handle all requests using just 1 thread.
Static call like this won't return expected results anymore:
SecurityContextHolder.getContext().getAuthentication();
Because there is no way to use ThreadLocal objects anymore.
The only way to get Authentication for you, is to ask for it in controller's method signature, or...
Return a reactive-chain from method, that is making a ReactiveSecurityContextHolder.getContext()
call.
Since you are returning a chain of reactive operators, Spring make a subscription to your chain, in order to execute it.
When Spring does it, it provides a security context to whole chain. Thus every call ReactiveSecurityContextHolder.getContext()
inside this chain, will return expected data.
Your can read more about Mono/Flux context here, because it is a Reactor-specific feature.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…