The Java EE 5 Tutorial

Example: Basic Authentication with a Servlet

This example discusses how to use basic authentication with a servlet. With basic authentication of a servlet, the web browser presents a standard login dialog that is not customizable. When a user submits their name and password, the server determines if the user name and password are those of an authorized user and sends the requested web resource if the user is authorized to view it. If the topic of authentication is new to you, please refer to the section Specifying an Authentication Mechanism.

In general, the following steps are necessary for adding basic authentication to an unsecured servlet, such as the one described in Web Modules. In the example application included with this tutorial, many of these steps have been completed for you and are listed here simply to show what needs to be done should you wish to create a similar application. The completed version of this example application can be found in the directory tut-install/javaeetutorial5/examples/web/hello2_basicauth/.

    The following steps describe how to set up your system for running the example applications, describe the sample application, and provide the steps for compiling, packaging, deploying, and testing the example application.

  1. If you have not already done so, set up your system so that the Ant tool and/or NetBeans IDE will run properly. To do this, follow the instructions in Building the Examples. This step is necessary to set the properties that are specific to your installation of the Application Server and Java EE 5 Tutorial.

  2. If you have not already done so, add an authorized user to the Application Server. For this example, add users to the file realm of the Application Server and assign the user to the group user. This topic is discussed more in Adding Authorized Roles and Users.

  3. Create a web module as described in Web Modules for the servlet example, hello2. The subsequent steps discuss adding security to this basic application. The files for this example application are in tut-install/javaeetutorial5/examples/web/hello2_basicauth/.

  4. Declare the roles that will be used in this application. For this example, this is done by adding the @DeclareRoles annotation to GreetingServlet.java. This code is shown in Declaring Security Roles.

  5. Add the appropriate security elements to the web.xml deployment descriptor. The deployment descriptor for the example application can be viewed at tut-install/javaeetutorial5/examples/web/hello2_basicauth/web/WEB-INF/web.xml. The security elements are described in Specifying the Security Constraint.

  6. Map the role name defined for this resource (helloUser) to a group of users defined on the Application Server. For more information on how to do this, read Mapping Application Roles to Application Server Groups.

  7. Build, package, and deploy the web application by following the steps in Building, Packaging, and Deploying the Servlet Basic Authentication Example Using NetBeans IDE or Building, Packaging, and Deploying the Servlet Basic Authentication Example Using Ant.

  8. Run the web application by following the steps described in Running the Basic Authentication Servlet.

  9. If you have any problems running this example, refer to the troubleshooting tips in Troubleshooting the Basic Authentication Example.

Declaring Security Roles

There are two annotations that can be used with servlets: @DeclareRoles and @RunAs. In this example, the @DeclareRoles annotation is used to specify which roles are referenced in this example.

The following section of the tut-install/javaeetutorial5/examples/web/hello2_basicauth/src/servlets/GreetingServlet.java file contains the code necessary to declare that the role of helloUser is used in this application:

package servlets;

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.annotation.security.DeclareRoles;
/**
* This is a simple example of an HTTP Servlet that can only be accessed
* by an authenticated user.  It responds to the GET
* method of the HTTP protocol.
*/
@DeclareRoles("helloUser")
public class GreetingServlet extends HttpServlet {

    public void doGet (HttpServletRequest request,
        HttpServletResponse response)
            throws ServletException, IOException

You could also declare security roles using the <security-role> element in the deployment descriptor. If you prefer to declare security roles this way, read Declaring Roles Using Deployment Descriptor Elements.

Specifying the Security Constraint

This example takes a very simple servlet-based web application and adds basic authentication to this application. The servlet is basically the same as the servlet used in the example described in Web Modules, with the exception of the annotations added and discussed in Declaring Security Roles.

The security constraint for this example is declared in the application deployment descriptor. The security constraint tells the server or browser to perform the following tasks:

Deployment descriptors elements are described in Declaring Security Requirements in a Deployment Descriptor.

The following sample code shows the security elements for the deployment descriptor used in this example of basic authentication, which can be found in tut-install/javaeetutorial5/examples/web/hello2_basicauth/web/WEB-INF/web.xml.

    <security-constraint>
        <display-name>SecurityConstraint</display-name>
        <web-resource-collection>
             <web-resource-name>WRCollection</web-resource-name>
            <url-pattern>/greeting</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>helloUser</role-name>
        </auth-constraint>
        <user-data-constraint>
             <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>file</realm-name>
    </login-config>

More description of the elements that declare security in a deployment descriptor can be found in Specifying Security Constraints.

Protecting Passwords with SSL

Passwords are not protected for confidentiality with HTTP basic or form-based authentication, meaning that passwords sent between a client and a server on an unprotected session can be viewed and intercepted by third parties. To overcome this limitation, you can run these authentication protocols over an SSL-protected session and ensure that all message content is protected for confidentiality.

A <transport-guarantee> element indicates whether or not the protected resources should travel over protected transport. For simplicity, this example does not require protected transport, but in a real world application, you would want to set this value to CONFIDENTIAL to ensure that the user name and password are not observed during transmission. When running on protected transport, you need to use the secure SSL protocol, https, and specify the secure port where your SSL connector is created (the default for the Application Server is 8181).

Adding Authorized Roles and Users

To authenticate a user and allow that user access to protected resources on the Application Server, you must link the roles defined in the application to the users defined for the Application Server.

When an application is deployed, the application-specific security roles are mapped to security identities in the runtime environment, such as principals (identities assigned to users as a result of authentication) or groups. Based on this mapping, a user who has been assigned a certain security role has associated access rights to a web application deployed onto a server.

As shown in the deployment descriptor for this example application, the security constraint specifies that users assigned to the role of helloUser are authorized to access the URL pattern /greeting. In this example, when this resource (because it is constrained by a security constraint) is accessed, the Application Server sends a default login dialog, receives the login information, and checks to see if the user is in a group that has been mapped to the role of helloUser. If the user name and password are those of an authorized user, access to the resource is granted to the requester.

    To set up users for this example application, follow these steps:

  1. If you have not already done so, create a user in the file realm of the Application Server and assign that user to the group user. Make sure to note the user name and password that you enter in this step so that you can use it for testing the application later. If you need help with the steps required to accomplish this task, read Managing Users and Groups on the Application Server for more information.

  2. Map the application security role of helloUser to the group of user that has been configured on the Application Server. For more information on how to do this mapping, read Mapping Application Roles to Application Server Groups.

Mapping Application Roles to Application Server Groups

Map the role of helloUser defined in the application to the group of user defined on the Application Server by adding a security-role-mapping element to the sun-web.xml runtime deployment descriptor file. The runtime deployment descriptor is an XML file that contains information such as the context root of the web application and the mapping of the portable names of an application’s resources to the Application Server’s resources.

The runtime deployment descriptor for this example, tut-install/javaeetutorial5/examples/web/hello2_basicauth/web/WEB-INF/sun-web.xml, looks like this:

<sun-web-app>
    <context-root>/hello2_basicauth</context-root>
    <security-role-mapping>
        <role-name>helloUser</role-name>
        <group-name>user</group-name>
    </security-role-mapping>
</sun-web-app>

Building, Packaging, and Deploying the Servlet Basic Authentication Example Using NetBeans IDE

    To build, package, and deploy the web/hello2_basicauth example application using NetBeans IDE, follow these steps:

  1. If you have not already done so, follow the instructions in Building the Examples. This step is necessary to provide the Ant targets with the location of your tutorial and Application Server installations.

  2. If you have not already done so, add authorized users to the file realm of the Application Server as described in Adding Authorized Roles and Users.

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

  4. Browse to the tut-installjavaeetutorial5/examples/web/hello2_basicauth/ directory.

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

  6. Select Open Project.

  7. Right-click hello2_basicauth in the Projects pane, then select Clean and Build.

  8. Right-click hello2_basicauth in the Projects pane, then select Undeploy and Deploy.

  9. To run the servlet, follow the steps in Running the Basic Authentication Servlet.

Building, Packaging, and Deploying the Servlet Basic Authentication Example Using Ant

    To build, package, and deploy the web/hello2_basicauth example using the Ant tool, follow these steps:

  1. If you have not already done so, follow the instructions in Building the Examples. This step is necessary to provide the Ant targets with the location of your tutorial and Application Server installations.

  2. If you have not already done so, add authorized users to the file realm of the Application Server as described in Adding Authorized Roles and Users.

  3. From a terminal window or command prompt, change to the tut-install/javaeetutorial5/examples/web/hello2_basicauth/ directory.

  4. Build and package the web application by entering the following command at the terminal window or command prompt:


    ant
    

    This command uses web.xml and sun-web.xml files, located in the tut-install/javaeetutorial5/examples/web/hello2_basicauth/web/WEB-INF/ directory.

  5. To deploy the example using Ant, enter the following command at the terminal window or command prompt:


    ant deploy
    

    The deploy target in this case gives you an incorrect URL to run the application. To run the application, please use the URL shown in Running the Basic Authentication Servlet.

  6. To run the web application, follow the steps in Running the Basic Authentication Servlet.

Running the Basic Authentication Servlet

    To run the web client, follow these steps:

  1. Open a web browser.

  2. Enter the following URL in your web browser:

    http://localhost:8080/hello2_basicauth/greeting

    If you set the transport guarantee to CONFIDENTIAL as discussed in Protecting Passwords with SSL, you must load the application in a web browser using https for the protocol, the HTTPS port that you specified during installation for the port (by default this port is 8181), and the context name for the application you wish to run. For the basic authentication example, you could run the example using the following URL: https://localhost:8181/hello2_basicauth/greeting.

  3. A default login form displays. Enter a user name and password combination that corresponds to a user that has already been created in the file realm of the Application Server and has been assigned to the group of user, as discussed in Adding Authorized Roles and Users.

    Basic authentication is case-sensitive for both the user name and password, so enter the user name and password exactly as defined for the Application 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 Application 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 Application Server.

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

    • The role of helloUser, as defined for the application, is mapped to the group of user, as defined for the Application Server.

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

  4. 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 30–10.

Figure 30–9 Running the Application

Screen shot of running basic authentication example showing
text field for user to type name

Figure 30–10 The Running Basic Authentication Example

Screen shot of running basic authentication example 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 targets or the NetBeans IDE Clean and Build option to get a fresh start.


Troubleshooting the Basic Authentication Example

    When doing iterative development with this web application, follow these steps if you are using NetBeans IDE:

  1. Close your web browser.

  2. Clean and recompile the files from the previous build by right-clicking hello2_basicauth and selecting Clean and Build.

  3. Redeploy the application by right-clicking hello2_basicauth and selecting Undeploy and Deploy.

  4. Open your web browser and reload the following URL:

    http://localhost:8080/hello2_basicauth/greeting

    Follow these steps if you are using the Ant tool:

  1. Close your web browser.

  2. Undeploy the web application. To undeploy the application, use the following command in the directory:


    ant undeploy
    
  3. Clean out files from the previous build, using the following command:


    ant clean
    
  4. Recompile, repackage, and redeploy the application, using the following commands:


    ant 
    ant deploy
    
  5. Open your web browser and reload the following URL:

    http://localhost:8080/hello2_basicauth/greeting