This is an issue with the Spring Security Keycloak Adapter relating to
the way the Authentication is stored in the SecurityContext, causing a
race condition in application code using that. It does not seem to
affect actual Spring Security operation.
We had a pretty strange race condition in our application. When many
requests were incoming at the same time, occasionally the old
unauthenticated Authentication provided to
KeycloakAuthenticationProvider for performing the actual authentication
would stay the current authentication, as returned by
SecurityContextHolder.getContext().getAuthentication(). That resulted
in authenticated users' JavaScript requests occasionally (~1/50 given a
large request volume) returning a 403 because the 'old' token was still
in the context, causing Spring Security to see them as unauthenticated.
This PR resolves this issue by replacing the whole context, as suggested
by a Spring Security contributor in jzheaux/spring-security-oauth2-resource-server#48. By default,
SecurityContextHolder keeps the actual context object in a ThreadLocal,
which should be safe from race-conditions. The actual Authentication
object, however, is kept in a mere field, hence the reason for this PR.
JIRA issue: https://issues.jboss.org/browse/KEYCLOAK-9539
The root cause is that NodesRegistrationManagement.tryRegister can be
called from multiple threads on the same node, so it can require
registration of the same node multiple times. Hence once it turns to
tasks that invoke sendRegistrationEvent (called sequentially), the same
check has been added to that method to prevent multiple invocations on
server side, or invocation upon undeployment/termination.
* PreAuthActionsFilter registers deployment during authentication attempt to enable, well,
node registration if filter is used by itself (if no securityConstraints when using spring boot and spring security)
* deregistering node during clean shutdown
* added unit test