background image

Checking Caller Identity Programmatically

<< Mapping Security Roles | Declaring Roles Using Annotations >>
<< Mapping Security Roles | Declaring Roles Using Annotations >>

Checking Caller Identity Programmatically

Checking Caller Identity Programmatically
In general, security management should be enforced by the container in a manner that is
transparent to the web component. The security API described in this section should be used
only in the less frequent situations in which the web component methods need to access the
security context information.
The HttpServletRequest interface provides the following methods that enable you to
access security information about the component's caller:getRemoteUser: Determines the
user name with which the client authenticated. If no user has been authenticated, this
method returns null.
isUserInRole
: Determines whether a remote user is in a specific security role. If no user has
been authenticated, this method returns false. This method expects a String user
role-name
parameter.
You can use either the @DeclareRoles annotation or the <security-role-ref> element
with a <role-name> sub-element in the deployment descriptor to pass the role name to this
method. Using security role references is discussed in
"Declaring and Linking Role
References" on page 846
.
getUserPrincipal
: Determines the principal name of the current user and returns a
java.security.Principal
object. If no user has been authenticated, this method returns
null
.
Your application can make business logic decisions based on the information obtained using
these APIs.
The following is a code snippet from an index.jsp file that uses these methods to access
security information about the component's caller.
<%@ taglib prefix=
"fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:setBundle basename=
"LocalStrings"/>
<html>
<head>
<title><fmt:message key=
"index.jsp.title"/>/title>
</head>
<body bgcolor=
"white">
<fmt:message key=
"index.jsp.remoteuser"/>
<b><%= request.getRemoteUser() %>
</b><br><br>
<%
if (request.getUserPrincipal() != null) {
%>
<fmt:message key=
"index.jsp.principal"/> <b>
<%= request.getUserPrincipal().getName() %></b><br><br>
Checking Caller Identity Programmatically
Chapter 30 · Securing Web Applications
845