background image

EJBContext Interface

<< Accessing an Enterprise Bean | Declaring Security Role Names >>
<< Accessing an Enterprise Bean | Declaring Security Role Names >>

EJBContext Interface

The javax.ejb.EJBContext interface provides two methods that allow the bean provider to
access security information about the enterprise bean's caller.
java.security.Principal getCallerPrincipal();
The purpose of the getCallerPrincipal method is to allow the enterprise bean methods to
obtain the current caller principal's name. The methods might, for example, use the name as
a key to information in a database.
boolean isCallerInRole(String roleName);
The purpose of the isCallerInRole(String roleName) method is to test whether the
current caller has been assigned to a given security role. Security roles are defined by the
bean provider or the application assembler, and are assigned to principals or principals
groups that exist in the operational environment by the deployer.
The following code sample illustrates the use of the getCallerPrincipal() method:
@Stateless public class EmployeeServiceBean
implements EmployeeService{
@Resource SessionContext ctx;
@PersistenceContext EntityManager em;
public void changePhoneNumber(...) {
...
// obtain the caller principal.
callerPrincipal = ctx.getCallerPrincipal();
// obtain the caller principal
's name.
callerKey = callerPrincipal.getName();
// use callerKey as primary key to find EmployeeRecord
EmployeeRecord myEmployeeRecord =
em.findByPrimaryKey(EmployeeRecord.class, callerKey);
// update phone number
myEmployeeRecord.setPhoneNumber(...);
...
}
}
In the previous example, the enterprise bean obtains the principal name of the current caller
and uses it as the primary key to locate an EmployeeRecord entity. This example assumes that
application has been deployed such that the current caller principal contains the primary key
used for the identification of employees (for example, employee number).
The following code sample illustrates the use of the isCallerInRole(String roleName)
method:
Securing Enterprise Beans
The Java EE 5 Tutorial · September 2007
800