How to Use Authentication Data in Servlets
When a user is logged in, servlets can get the user's name and check her roles. This is only possible in combination with declarative security, because the container authenticates users only for restricted resources (more).
The ServletRequest provides you with three methods to access authentication data:
- getUserPrincipal returns the user's Principal object (more), or null if no user is logged in
- getRemoteUser returns the user's login name, or null if no user is logged in
- isUserInRole checks whether the current user is in the given role
Getting the User's Identity
This example logs the authenticated user:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Principal p = request.getUserPrincipal();
if (p == null)
log("No user logged in.");
else {
log("Principal: " + p.getName());
log("User name: " + request.getRemoteUser());
}
// ...
}
Role Checking
You can use isUserInRole to check whether the user is in the specified role. This code checks the user's roles:
HttpServletRequest request = ...;
if ( request.isUserInRole("root") ||
(request.isUserInRole("privileged") &&
request.isUserInRole("merchandise")) ) {
// user authenticated
}
By default, the argument to isUserInRole is a role decared in the web.xml deployment descriptor using <security-role> (see user management). If your servlet needs different names, it map the name in its declaration:
<servlet> <servlet-name>adminServlet</servlet-name> <servlet-class>com.jarfiller.example.AdminServlet</servlet-class> <security-role-ref> <role-name>root</role-name> <!-- the servlet's internal name --> <role-link>admin</role-link> <!-- the application's name in <security-role> --> </security-role-ref> <security-role-ref> <role-name>privileged</role-name> <!-- the servlet's internal name --> <role-link>super-user</role-link> <!-- the application's name in <security-role> --> </security-role-ref> <security-role-ref> <role-name>merchandise</role-name> <!-- the servlet's internal name --> <role-link>merch-user</role-link> <!-- the application's name in <security-role> --> </security-role-ref> </servlet>

