The Java EE 5 Tutorial

Protecting the Web Client Resources

In the JavaEE platform, you protect a web resource from anonymous access by specifying which security roles can access the resource. The web container guarantees that only certain users acting in those roles can access the resource. For the web container to enforce the security constraint, the application must specify a means for users to identify themselves, and the web container must support mapping a role to a user.

In the Duke’s Bank web client, you restrict all the URLs listed in Table 37–2 to the security role bankCustomer. The application requires users to identify themselves by means of the form-based login mechanism. When a customer tries to access a web client URL and has not been authenticated, the web container displays the JSP page logon.jsp. This page contains an HTML form that requires a customer to enter an identifier and password. This form is rendered by a JavaServer Faces custom component. A custom tag represents the component on the page. In the following piece of logon.jsp, the <db:formBasedLogin> tag represents the custom component:

<f:view>
...
<h:outputText value="#{bundle.Logon}"/>
 <h:outputText value="#{bundle.Submit}"/>.</h3>
<br><br>
<db:formBasedLogin  />
</f:view>

Note that there is no h:form tag. This is because the custom component renders the form tag along with the complete HTML form that customers use to log in:

<form action="j_security_check" method=post>
<table>
<tr>
    <td align="center" >
    <table border="0">
    <tr>
    <td><b><fmt:message key="CustomerId"/></b></td>
    <td>
        <input type="text" size="15" name="j_username">
     </td>
    </tr>
    <tr>
    <td><b><fmt:message key="Password"/></b></td>
    <td>
         <input type="password" size="15" name="j_password">
    </td>
    ...
</form>

    Note that the action invoked by the form, j_security_check, is specified by the Java Servlet specification, as are the request parameters j_username and j_password. The web container retrieves this information, maps it to a security role, and verifies that the role matches that specified in the security constraint. In order for the web container to check the validity of the authentication information and perform the mapping, you must perform these two steps when you deploy the application:

  1. Add the customer’s group, ID, and password to the default realm of the container using the Admin Console.

  2. Map the bankCustomer role to the customer or the customer’s group in the deployment descriptor.

After the customer has been authenticated, the identifier provided by the customer is used as a key to identify the customer’s accounts. The identifier is retrieved from the FacesContext object by the CustomerBean constructor, which saves it into the customerId property:

customerId = Long.parseLong(FacesContext.getCurrentInstance()
    .getExternalContext().getUserPrincipal().getName());