I have an custom controller API which I have to keep anonymous for business reasons but I send 1 of user ids in the body payload. Then in respective service I do authentication.begin as that user. If I see user in user session its correct and then I create the entity.
But I have a entity listener for on before insert where I need to fetch that user from user session source but I still get anonymous there. I started noticing it recently because of some transaction changes I made but cannot point out why entity listener is not in same transaction.
Maybe your problem is caused by the fact that Authentication.begin(username) does not necessarily creates a session for the specified user if a valid session already set for the thread. This is documented on the Javadoc of this method.
I knew that and was calling authetication.end() just before setting my user. I even verified that it was set by fetching login name from user session source.
My problem was that I added a @Transactional on this service method. Now in the end of service method I was resetting the ‘anonymous’ login in the session. What I believe is although I requested dataManager.persist while I was acting as a user, the transaction commit only happened after the method exit at which point user was again anonymous and then the before insert listener got triggered.
I solved this by removing the @Transactional from my method so I think its now commit just in time or sharing controller transaction (not sure) but working as intended.
I do not like my solution above and not sure the behaviour I observed is correct or a bug. IMHO before insert entity listener should share the same transaction and should be called before commit. Not sure currently what will happen if I throw an error from the listener.