Example: Enterprise bean applications code
This enterprise bean component example illustrates the usage of the isCallerInRole() and getCallerPrincipal() methods in an EJB module. It is recommended that the declarative security be used if possible. The example demonstrates one way of using the isCallerInRole() and getCallerPrincipal() result, and not the only way to use these methods. The application can make use of this result in any way that is suitable for the application.
See the Code example disclaimer for legal information about this code example.
Remote interface
// File : Hello.java package tests; import java.rmi.RemoteException; public interface Hello extends javax.ejb.EJBObject { public abstract String getMessage()throws RemoteException; public abstract void setMessage(String s)throws RemoteException; }Home interface
// File : HelloHome.java package tests; import java.rmi.RemoteException; public interface HelloHome extends javax.ejb.EJBHome { public tests.Hello create() throws javax.ejb.CreateException, RemoteException; }Bean implementation
// File : HelloBean.java package tests; public class HelloBean implements javax.ejb.SessionBean { private javax.ejb.SessionContext mySessionCtx; public javax.ejb.SessionContext getSessionContext() { return mySessionCtx; } public void setSessionContext(javax.ejb.SessionContext ctx) { mySessionCtx = ctx; } public void ejbActivate() { } public void ejbCreate() throws javax.ejb.CreateException { } public void ejbPassivate() { } public void ejbRemove() { } public java.lang.String message; // Business methods // all users can call getMessage() public String getMessage() throws java.rmi.RemoteException { return message; } // all users can call setMessage() but only few users can set new message. public void setMessage(String s) throws java.rmi.RemoteException { // get bean's caller using getCallerPrincipal() java.security.Principal principal = mySessionCtx.getCallerPrincipal(); java.lang.String callerId= principal.getName(); // check if bean's caller is granted Mgr role boolean isMgr = mySessionCtx.isCallerInRole("Mgr"); // only set supplied message if caller is "bob" or caller is granted Mgr role if ( isMgr || callerId.equals("bob") ) message = s; else message = "Hello"; } }After you develop the entity bean, create a security role reference in the deployment descriptor under the session bean, Hello, as shown below:
<security-role-ref> <description>Only Managers can call setMessage() on this bean (Hello)</description> <role-name>Mgr</role-name> </security-role-ref>