I have a simple (webprofile) EJB 3.1 application and try to determine the current user in the @ApplicationScoped
CDI Bean, so I use:
Principal callerPrincipal = this.sessionContext.getCallerPrincipal()
works fine (so I can determine the name of the current user).
But after any exception in any (other) EJB, this call no longer works (I need to restart the server)! Instead of returning the main call to the caller, the method throws this exception.
Caused by: java.lang.NullPointerException at com.sun.ejb.containers.EJBContextImpl.getCallerPrincipal(EJBContextImpl.java:421) at de.mytest.service.CurrentUserService.getCurrentUserId(CurrentUserService.java:102)
Can anyone give me a hint what am I doing wrong?
Implementation Details:
Glassfish 3.1.2 Server
CurrentUserService:
@ApplicationScoped public class CurrentUserService { @Resource private SessionContext sessionContext; public long getCurrentUserId() { if (this.sessionContext == null) { throw new RuntimeException("initialization error, sessionContext must not be null!"); } Principal callerPrincipal = this.sessionContext.getCallerPrincipal(); if (callerPrincipal == null) { throw new RuntimeException("callerPrincipal must not be null, but it is"); } String name = callerPrincipal.getName(); if (name == null) { throw new RuntimeException("could not determine the current user id, because no prinicial in session context"); } return this.getUserIdForLogin(name); }
EJB Facad Resist Between Faces Controller and CDI Service
@Stateless @RolesAllowed("myUser") public class TeilnehmerServiceEjb { @Inject private CurrentUserService currentUserService; public long currentUserId() { return = currentUserService.getCurrentUserId(); } }
web.xml
<security-constraint> <web-resource-collection> <web-resource-name>All Pages</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>myUser</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>mySecurityRealm</realm-name> </login-config>
GlassFish-web.xml
<security-role-mapping> <role-name>myUser</role-name> <group-name>APP.MY.USER</group-name> </security-role-mapping>
Ralph source share