The Java EE 6 Tutorial, Volume I

Example: Form-Based Authentication with a Servlet

This example discusses how to use form-based authentication with a basic servlet. With form-based authentication, you can customize the login screen and error pages that are presented to the web client for authentication of their user name and password. When a user submits their name and password, the server determines if the user name and password are those of an authorized user and, if authorized, sends the requested web resource.

In general, the steps are necessary for adding form-based authentication to an unsecured servlet are similar to those described in Example: Basic Authentication with a Servlet, so just follow all of the steps in Example: Basic Authentication with a Servlet, except use the deployment descriptor described in Specifying Security in the Deployment Descriptor instead and create the login form and login error form pages as described in Creating the Login Form and the Error Page. The completed version of this example application can be found in the directory tut-install/examples/web/hello2_formauth/.

Creating the Login Form and the Error Page

When using form-based login mechanisms, you must specify a page that contains the form you want to use to obtain the user name and password, as well as which page to display if login authentication fails. This section discusses the login form and the error page used in this example. The section Specifying Security in the Deployment Descriptor shows how you specify these pages in the deployment descriptor.

The login page can be an HTML page, a JSP page, or a servlet, and it must return an HTML page containing a form that conforms to specific naming conventions (see the Java Servlet 3.0 specification for more information on these requirements). To do this, include the elements that accept user name and password information between <form></form> tags in your login page. The content of an HTML page, JSP page, or servlet for a login page should be coded as follows:

<form method=post action="j_security_check" >
    <input type="text"  name= "j_username" >
    <input type="password"  name= "j_password" >
</form>

The full code for the login page used in this example can be found at tut-install/examples/web/hello2_formauth/web/loginform.html. An example of the running login form page is shown later in Figure 25–8. Here is the code for this page:

<html>
<head>
    <title>Login Page</title>
</head>

<h2>Hello, please log in:</h2>
<br><br>
<form action="j_security_check" method=post>
    <p><strong>Please Enter Your User Name: </strong>
    <input type="text" name="j_username" size="25">
    <p><p><strong>Please Enter Your Password: </strong>
    <input type="password" size="15" name="j_password">
    <p><p>
    <input type="submit" value="Submit">
    <input type="reset" value="Reset">
</form>
</html>

The login error page is displayed if the user enters a user name and password combination that is not authorized to access the protected URI. For this example, the login error page can be found at tut-install/examples/web/hello2_formauth/web/loginerror.html. For this example, the login error page explains the reason for receiving the error page and provides a link that will allow the user to try again. Here is the code for this page:

<html>
<head>
    <title>Login Error</title>
</head>
<body>
    <c:url var="url" value="/index.jsp"/>
    <h2>Invalid user name or password.</h2>

    <p>Please enter a user name or password that is authorized to access this 
    application. For this application, this means a user that has been created in the 
    <code>file</code> realm and has been assigned to the <em>group</em> of 
    <code>TutorialUser</code>.  Click here to <a href="${url}">Try Again</a></p>
</body>
</html>

Specifying Security in the Deployment Descriptor

This example takes a very simple servlet-based web application and adds form-based security to this application. All security for this example is declared in the deployment descriptor for the application. A security constraint is defined in the deployment descriptor that tells the server to send a login form to collect user data, verify that the user is authorized to access the application, and, if so, display the JSP page to the user.

Deployment descriptor elements are described in Introduction to Web Application Deployment Descriptors.

The following sample code shows the deployment descriptor used in this example of form-based login authentication, which can be found in tut-install/examples/web/hello2_formauth/web/WEB-INF/web.xml.

<!-- FORM-BASED LOGIN AUTHENTICATION EXAMPLE -->
<?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>hello2_formauth</display-name>
       <servlet>
             <display-name>index</display-name>
            <servlet-name>index</servlet-name>
            <jsp-file>/index.jsp</jsp-file>
      </servlet>
     <security-constraint>
             <display-name>SecurityConstraint</display-name>
            <web-resource-collection>
                  <web-resource-name>WRCollection</web-resource-name>
                 <url-pattern>/*</url-pattern>
         </web-resource-collection>
            <auth-constraint>
                  <role-name>TutorialUser</role-name>
            </auth-constraint>
            <user-data-constraint>
                <transport-guarantee>CONFIDENTIAL</transport-guarantee>
            </user-data-constraint>
       </security-constraint>
      <login-config>
            <auth-method>FORM</auth-method>
         <form-login-config>
                  <form-login-page>/loginform.html</form-login-page>
                 <form-error-page>/loginerror.html</form-error-page>
          </form-login-config>
     </login-config>
     <security-role>
        <role-name>TutorialUser</role-name>
    </security-role>
</web-app>

Building, Packaging, and Deploying the Form-Based Authentication Example Using NetBeans IDE

    To build, package, and deploy this application using NetBeans IDE, follow these steps:

  1. Follow the steps in Setting Up Your System for Running the Security Examples.

  2. Open the project in NetBeans IDE by selecting File->Open Project.

  3. Browse to the tut-install/examples/web/hello2_formauth/ directory.

  4. Make sure that Open as Main Project is selected.

  5. Select Open Project.

  6. Right-click hello2_formauth in the Projects pane, then select Clean and Build.

  7. Right-click hello2_formauth in the Projects pane, then select Deploy.

  8. Follow the steps in Testing the Form-Based Authentication Web Client.

Building, Packaging, and Deploying the Form-Based Authentication Example Using Ant

    To build, package, and deploy this application using the Ant tool, follow these steps:

  1. Follow the steps in Setting Up Your System for Running the Security Examples.

  2. From a terminal window or command prompt, change to the tut-install/examples/web/hello2_formauth/ directory.

  3. Enter the following command at the terminal window or command prompt:


    ant
    

    This target will spawn any necessary compilations, copy files to the tut-install/examples/web/hello2_formauth/build/ directory, create the WAR file, and copy it to the tut-install/examples/web/hello2_formauth/dist/ directory.

  4. Deploy the WAR named hello2_formauth.war onto the Enterprise Server using Ant by entering the following command at the terminal window or command prompt:


    ant deploy
    
  5. Follow the steps in Testing the Form-Based Authentication Web Client.

Testing the Form-Based Authentication Web Client

    To run the web client, follow these steps:

  1. Open a web browser.

  2. Enter the following URL in your web browser:

    https://localhost:8181/hello2_formauth

    The login form displays in the browser, as shown in Figure 25–8.

  3. Enter a user name and password combination that corresponds to a user that has already been created in the file realm of the Enterprise Server and has been assigned to the group of TutorialUser.

  4. Click the Submit button. Form-based authentication is case-sensitive for both the user name and password, so enter the user name and password exactly as defined for the Enterprise Server.

    If you entered My_Name as the name and My_Pwd for the password, the server returns the requested resource if all of the following conditions are met:

    • There is a user defined for the Enterprise Server with the user name of My_Name.

    • The user with the user name of My_Name has a password of My_Pwd defined for the Enterprise Server.

    • The user My_Name with the password My_Pwd is assigned to the group of TutorialUser on the Enterprise Server.

    • The role of TutorialUser, as defined for the application, is mapped to the group of TutorialUser, as defined for the Enterprise Server.

      When these conditions are met, and the server has authenticated the user, the application will display as shown in Figure 25–9.

  5. Enter your name and click the Submit button. Because you have already been authorized, the name you enter in this step does not have any limitations. You have unlimited access to the application now.

    The application responds by saying “Hello” to you, as shown in Figure 25–10.

For additional testing, close and reopen your browser, enter the application URL, and enter a username and password that are not authorized to see the login error page generated.

Figure 25–8 Form-Based Login Page

Screen shot of form-based login page showing text fields
for user name and password

Figure 25–9 Running Web Application

Screen shot of running form-based web application with
text field for user to type name

Figure 25–10 The Running Form-Based Authentication Example

Screen shot of running form-based web application showing
response


Note –

For repetitive testing of this example, you may need to close and reopen your browser. You should also run the ant clean and ant undeploy commands to ensure a fresh build if using the Ant tool, or select Clean and Build then Undeploy and Deploy if using NetBeans IDE.