I have something like this setup below. This is a simplified version but I think it gets the basic idea across. I am using Jersey 2.16, Java 1.8, and Glassfish Open Source 4
Thank you, I have solved using the EJBContext inside the EJBs, as pointed by unwichtich.
In conclusion, SecurityContext is only for the JAX-RS bean, I have used the EJBContext object inplace of SecurityContext into the other java beans. You can also use the SessionContext object but EJBContext interface resembles the SecurityContext one. Here is an usage example:
@DeclareRoles({"administrator","operator","user"})
@PermitAll
@Stateless
public class myFacade {
@PersistenceContext(unitName = "myPersistencePU")
private EntityManager em;
@Resource EJBContext securityContext;
public DataStuff find(Object id) {
//Now the securityContext is != null :-D
String username = securityContext.getCallerPrincipal().getName();
if(username.equals("gino"){
return null;
}
return getEntityManager().find(entityClass, id);
}
}
It works auto-magically as expected, the EJB sees the same Principal(s) as the JAX-RS servlet do.
The problem is that you are using the SecurityContext
in the wrong place. You have to use it inside your REST resource class.
You can try the following:
@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces(MediaType.TEXT_PLAIN)
@Override
public String addNewReport(final Report report, @Context SecurityContext sc) {
report.setUserName(sC.getUserPrincipal().getName());
return service.addNewReport(report);
}
For more details have a look at the Jersey Documentation - Chapter 16. Security.
Inside of EJBs you have to use the EJBContext (or the SessionContext).