Using programmatic security to custom-tailor a method

We just looked at getCallerPrincipal(), to see how you could find out exactly WHO the container believes is calling the method. But we can also use the isCallerInRole() method to test whether the principal (whoever it is and in this case we don’t care) is a member of a specific role that we do care about. Imagine that you have a private pricing method, called by one of your business methods, that checks to see if this customer authenticated as a member of your special VIP customer group. If he is, you treat him differently than if he isn’t. Maybe you give him a discount. Maybe you raise the price. Whatever your business logic tells you to do.

With isCallerInRole(), you can use security information to tailor the way a method runs, depending on which role called the method.

This is usually NOT a good way to handle security. To control access to a method, you’re much better off using the method permissions to stop an unauthorized role from ever calling the method.

But you can still USE the caller’s role information to do other non-security things in your code.

private void determinePrice() {

    if (context.isCallerInRole("VIPCustomer")) {
       // treat customer well
    } else {
      // treat him like the loser he is
    }
}

Besides the obvious problem with hard-coding security information (cuts down your reuse, increases the chances that things won’t work in a portable way, etc.), there’s another big problem—how the heck does the Bean Provider know in advance ...

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.