Saturday, December 26, 2009

EJB Security: Logging the user that invokes a session bean method

If you have a requirement to log the user who created or updated a certain record. You can do so by getting the CallerPrincipal object in the SessionContext of an EJB session bean. The SessionContext can be injected in a session bean using the @Resource annotation. Please see below a sample session bean with an injected SessionContext plus the call to get the CallerPrincipal object:
package oracle;

import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless(name = "HRFacade", mappedName = "HR_EJB_JPA_App-EJBModel-HRFacade")
@Remote
@Local
public class HRFacadeBean implements HRFacade, HRFacadeLocal {
    @PersistenceContext(unitName="EJBModel")
    private EntityManager em;
    @Resource
    private SessionContext context;

    public HRFacadeBean() {
    }
    public Employee mergeEmployee(Employee employee) {
        String username = context.getCallerPrincipal().getName();
        employee.setUpdatedBy(username);
        return em.merge(employee);
    }
...
}

No comments:

Post a Comment