I'm seeing some strange behaviour when using stateless token-based authentication on a rest API written using Spring Boot.
The client includes a JWT token with each request, and a custom filter I've written that extends GenericFilterBean adds an Authentication object based on the claims in the token to the security context using the following :
SecurityContextHolder.getContext().setAuthentication(authentication);
And clears the context after processing the request by doing :
SecurityContextHolder.getContext().setAuthentication(null);
However when the simple app I've developed performs a range of operations, I sometimes see that the security context isn't being set correctly - sometimes it's null for a request that has supplied a token. The filter is being called correctly, setAuthencation() is also being called, but the request fails authentication, and throws a 403 denied.
If I explicitly turn off any http Session management by setting the session creation policy to STATELESS, this behaviour stops.
Any ideas what could be happening here? Is the security context being shared between threads dealing with requests in some way?