Class-level vs. instance-level security

When declarative security is not enough, you might need programmatic security to restrict access to a specific instance of a bean.

So far, all the security we’ve looked at has been declarative...not hard-coded into the bean class. Declarative security is cool because it supports the whole idea of component-based development—you can customize the bean at deploy-time without touching the code. Company A might be using a bean in one application, and need a particular type of access control that’s completely different from the way Company B is using that same bean. Or even two uses of the same bean in the same company might need different access control.

But declarative security is at the class-level. You specify which methods a particular role can call, but it means that role can call the method on ANY instance of the bean class. If you need instance-level security, you can’t do it in the deployment descriptor. But you can do programmatic security, which of course you already know... you’ve seen the two security-related methods in SessionContext and EntityContext.

image with no caption
public void doSecurity() {
   java.security.Principal p = context.getCallerPrincipal();
   String name = p.getName();
   // now do a comparison by checking the name
   // against the persistent field in the bean
   // that should match the principal name
}

But be careful! There is no guarantee that the ...

Get Head First EJB now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.