Example: Enterprise bean application code

The following EJB component example illustrates the use of isCallerInRole() and getCallerPrincipal() methods in an EJB module. Using that declarative security is recommended. The following example is one way of using the isCallerInRole() and getCallerPrincipal() methods. The application can use this result in any way that is suitable.

 

A remote interface

File : Hello.java

package tests;
import java.rmi.RemoteException;
/**
* Remote interface for Enterprise Bean: Hello
*/
public interface Hello extends javax.ejb.EJBObject {
public abstract String getMessage()throws RemoteException;
public abstract void setMessage(String s)throws RemoteException;
}

 

A home interface

File : HelloHome.java
package tests;
/**
* Home interface for Enterprise Bean: Hello
*/
public interface HelloHome extends javax.ejb.EJBHome {
/**
* Creates a default instance of Session Bean: Hello
*/
public tests.Hello create() throws javax.ejb.CreateException,
java.rmi.RemoteException;
}

 

A bean implementation

File : HelloBean.java

package tests;
/**
* Bean implementation class for Enterprise Bean: Hello
*/
public class HelloBean implements javax.ejb.SessionBean {
private javax.ejb.SessionContext mySessionCtx;
/**
* getSessionContext
*/
public javax.ejb.SessionContext getSessionContext() {
return mySessionCtx;
}
/**
* setSessionContext
*/
public void setSessionContext(javax.ejb.SessionContext ctx) {
mySessionCtx = ctx;
}
/**
* ejbActivate
*/
public void ejbActivate() {
}
/**
* ejbCreate
*/
public void ejbCreate() throws javax.ejb.CreateException {
}
/**
* ejbPassivate
*/
public void ejbPassivate() {
}
/**
* ejbRemove
*/
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 development of the entity bean, create a security role reference in the deployment descriptor under the session bean, Hello:

<security-role-ref>
<description>Only Managers can call setMessage() on this bean (Hello)</description>
<role-name>Mgr</role-name>
</security-role-ref>

For an explanation of how to create a <security-role-ref> element, see Securing enterprise bean applications. Use the information under Map security-role-ref and role-name to role-link to create the element.


 

Related Tasks


Securing enterprise bean applications