Sorry for the long post, but I have tried to explain the problem in detail.
We are facing strange issues in getting the caller principal in our EJBs. Here is the envt we have:
We are using JBoss 4.2.0 GA. We are not using JAAS for authentication. A custom service is validating the credentials and returns a custom principal. The custom principal and password are set on the initial context:
context = new InitialContext(credentials);
along with other usual details.
This context is used to lookup the remote proxy in the client. So the invoked bean should now have the sessionContext populated with the customPrincipalInstance.
We also have an EJB interceptor that intercepts any ejb method invocation. If the principal available in the interceptor is not an instance of our CustomPrincipal it throws an exception.
We have the following invocation steps (along with interceptors) which we are testing:
Now when I start JBoss app server and access the client, the above steps should be undertaken. I am able to get the correct caller principal in EJB2 (EJB2 is injected into EJB1 using @EJB annotation) only at the third attempt. Here's what happens in each attempt:
First Attempt: Client passes customPrincipalInstance. In interceptor, the callerPrincipal returned by sessionConext is customPrincipalInstance. But, in EJB1, the callerPrincipal returned by sessionContext is SimplePrincipal (unauthenticated). So, when EJB1 invokes EJB2, the second interceptor fails, as the principal now in the context is SimplePrincipal.
Second Attempt: Client passes customPrincipalInstance. In interceptor, the callerPrincipal is customPrincipalInstance. This time in EJB1 also, the callerPrincipal is customPrincipalInstance. When EJB1 invokes EJB2, the second interceptor gets customPrincipalInstance. So EJB 2 gets invoked, but when I print the caller principal here, the value is SimplePrincipal (unauthenticated).
Third Attempt: Now everything works fine. Both the EJBs and the interceptors get customPrincipalInstance. No errors anywhere.
All further attempts also work fine.
I dont know why the first two invocations give error. I certainly cannot tell the client to login 3 times to get the app to work :). What could be the issue?
I checked the JBoss code, and found that threadPrincipal.get() in SecurityAssociation.getCallerPrincipal() returns the principal. But cannot understand why it doesnt work in first two attempts but works later.
Any help/input is appreciated.