Accessing an Enterprise Bean Caller’s Security Context

Chapter 11 - Security Management

    Accessing an Enterprise Bean Caller’s Security Context

  •           Security management used the container that is transparent to the enterprise beans’ business methods.

              The security API used less frequent situations in which the enterprise bean business methods need to access the security context information.

    The javax.ejb.EJBContext interface provides two methods:

                   •  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 be 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.

    @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(...);
    
            ...
        }
    }
    

    isCallerInRole(String roleName) method:

    @DeclareRoles("payroll")
    @Stateless public class PayrollBean implements Payroll {
         @Resource SessionContext ctx;
    
         public void updateEmployeeInfo(EmplInfo info) {
    
             oldInfo = ... read from database;
    
             // The salary field can be changed only by callers
             // who have the security role "payroll"
             if (info.salary != oldInfo.salary &&
                 !ctx.isCallerInRole("payroll")) {
                     throw new SecurityException(...);
             }
             ...
         }
         ...
     }
    

© 2015 by Learncertification All Rights Reserved. The certification names are the trademarks of their respective owners. Terms & Privacy Policy