We came across this in an environment of ours that uses a custom login module, but if I read the code correctly, this is a more general problem: if an authentication failure occurs while handling an EJB method, then the security context for the thread is not reset correctly, and subsequent uses of the thread for anonymous methods (e.g. timers) use the incorrect credentials.
I suspect the problem lies in SimpleSecurityManager's push() implementation, which is invoked from the SecurityContextInterceptor as follows:
@Override public Object processInvocation(final InterceptorContext context) throws Exception { // TODO - special cases need to be handled where SecurityContext not established or minimal unauthenticated principal context instead. doPrivileged(pushAction); try { return context.proceed(); } finally { doPrivileged(popAction); } }
If the pushAction throws an exception, then the popAction is never invoked. SimpleSecurityManager's push action starts off with
public void push(final String securityDomain) { // TODO - Handle a null securityDomain here? Yes I think so. final SecurityContext previous = SecurityContextAssociation.getSecurityContext(); contexts.push(previous); SecurityContext current = establishSecurityContext(securityDomain);
If an exception is subsequently raised, then the thread's security context is never reset (and previous is never popped off the "contexts" stack either).
If the same thread is subsequently used in a timer invocation that is supposed to run without a principal, the old security context is still active in the thread, and will be used incorrectly. (In our case leading to the same authentication exception over and over.)
I was able to successfully work around this issue by catching exceptions in push() and invoking pop() in the catch block, before rethrowing the exception.