O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Customizing methods: isUserInRole()

In HttpServletRequest, three methods are associated with programmatic security:

getUserPrincipal(), which is mainly used with EJBs. We won’t cover it in this book.[13]

getRemoteUser(), which can be used to check authentication status. It’s not commonly used, so we don’t cover it in this book (and there’s nothing else you need to know about it for the exam).

isUserInRole(), which we’ll look at now. Instead of authorizing at the HTTP method level (GET, POST, etc.), you can authorize access to portions of a method. This gives you a way to customize how a service method behaves based on the user’s role. If you’re in this service method (doGet(), doPost(), etc.), then the user made it through the declarative authorization, but now you want to do something in the method conditionally, based on wheher the user is in a particular role.

How do you match up roles in the DD with roles in a servlet?

image with no caption

How it works:

  1. Before isUserInRole() is called, the user needs to be authenticated. If the method is called on a user that has not been authenticated, the Container will always return false.

  2. The Container takes the isUserInRole() argument, in this example “Manager”, and compares it to the roles defined for the user in this request.

  3. If the user is mapped to this role, the Container returns true.

[13] We do, however, know of this really nice EJB book...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required