Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  JavaServer Faces Technology

5.  Introduction to Facelets

6.  Expression Language

7.  Using JavaServer Faces Technology in Web Pages

8.  Using Converters, Listeners, and Validators

9.  Developing with JavaServer Faces Technology

10.  JavaServer Faces Technology: Advanced Concepts

11.  Using Ajax with JavaServer Faces Technology

12.  Composite Components: Advanced Topics and Example

13.  Creating Custom UI Components and Other Custom Objects

14.  Configuring JavaServer Faces Applications

15.  Java Servlet Technology

16.  Uploading Files with Java Servlet Technology

17.  Internationalizing and Localizing Web Applications

Part III Web Services

18.  Introduction to Web Services

19.  Building Web Services with JAX-WS

20.  Building RESTful Web Services with JAX-RS

21.  JAX-RS: Advanced Topics and Example

Part IV Enterprise Beans

22.  Enterprise Beans

23.  Getting Started with Enterprise Beans

24.  Running the Enterprise Bean Examples

25.  A Message-Driven Bean Example

26.  Using the Embedded Enterprise Bean Container

27.  Using Asynchronous Method Invocation in Session Beans

Part V Contexts and Dependency Injection for the Java EE Platform

28.  Introduction to Contexts and Dependency Injection for the Java EE Platform

29.  Running the Basic Contexts and Dependency Injection Examples

30.  Contexts and Dependency Injection for the Java EE Platform: Advanced Topics

31.  Running the Advanced Contexts and Dependency Injection Examples

Part VI Persistence

32.  Introduction to the Java Persistence API

33.  Running the Persistence Examples

34.  The Java Persistence Query Language

35.  Using the Criteria API to Create Queries

36.  Creating and Using String-Based Criteria Queries

37.  Controlling Concurrent Access to Entity Data with Locking

38.  Using a Second-Level Cache with Java Persistence API Applications

Part VII Security

39.  Introduction to Security in the Java EE Platform

40.  Getting Started Securing Web Applications

Overview of Web Application Security

Securing Web Applications

Specifying Security Constraints

Specifying a Web Resource Collection

Specifying an Authorization Constraint

Specifying a Secure Connection

Specifying Security Constraints for Resources

Specifying Authentication Mechanisms

HTTP Basic Authentication

Form-Based Authentication

Digest Authentication

Specifying an Authentication Mechanism in the Deployment Descriptor

Declaring Security Roles

Using Programmatic Security with Web Applications

Authenticating Users Programmatically

Checking Caller Identity Programmatically

Example Code for Programmatic Security

Declaring and Linking Role References

41.  Getting Started Securing Enterprise Applications

42.  Java EE Security: Advanced Topics

Part VIII Java EE Supporting Technologies

43.  Introduction to Java EE Supporting Technologies

44.  Transactions

45.  Resources and Resource Adapters

46.  The Resource Adapter Example

47.  Java Message Service Concepts

48.  Java Message Service Examples

49.  Bean Validation: Advanced Topics

50.  Using Java EE Interceptors

Part IX Case Studies

51.  Duke's Bookstore Case Study Example

52.  Duke's Tutoring Case Study Example

53.  Duke's Forest Case Study Example

Index

 

Examples: Securing Web Applications

Some basic setup is required before any of the example applications will run correctly. The examples use annotations, programmatic security, and/or declarative security to demonstrate adding security to existing web applications.

Here are some other locations where you will find examples of securing various types of applications:

To Set Up Your System for Running the Security Examples

To set up your system for running the security examples, you need to configure a user database that the application can use for authenticating users. Before continuing, follow these steps.

  1. Add an authorized user to the GlassFish Server. For the examples in this chapter and in Chapter 41, Getting Started Securing Enterprise Applications, add a user to the file realm of the GlassFish Server, and assign the user to the group TutorialUser:
    1. From the Administration Console, expand the Configurations node, then expand the server-config node.
    2. Expand the Security node.
    3. Expand the Realms node.
    4. Select the File node.
    5. On the Edit Realm page, click Manage Users.
    6. On the File Users page, click New.
    7. In the User ID field, type a User ID.
    8. In the Group List field, type TutorialUser.
    9. In the New Password and Confirm New Password fields, type a password.
    10. Click OK.

    Be sure to write down the user name and password for the user you create so that you can use it for testing the example applications. Authentication is case sensitive for both the user name and password, so write down the user name and password exactly. This topic is discussed more in Managing Users and Groups on the GlassFish Server.

  2. Set up Default Principal to Role Mapping on the GlassFish Server:
    1. From the Administration Console, expand the Configurations node, then expand the server-config node.
    2. Select the Security node.
    3. Select the Default Principal to Role Mapping Enabled check box.
    4. Click Save.

The hello2_basicauth Example: Basic Authentication with a Servlet

This example explains 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 his or her name and password, the server determines whether 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.

In general, the following steps are necessary for adding basic authentication to an unsecured servlet, such as the ones described in Chapter 3, Getting Started with Web Applications. 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 tut-install/examples/security/hello2_basicauth/ directory.

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

  2. Create a web module as described in Chapter 3, Getting Started with Web Applications for the servlet example, hello2.

  3. Add the appropriate security annotations to the servlet. The security annotations are described in Specifying Security for Basic Authentication Using Annotations.

  4. Build, package, and deploy the web application by following the steps in To Build, Package, and Deploy the hello2_basicauth Example Using NetBeans IDE or To Build, Package, and Deploy the hello2_basicauth Example Using Ant.

  5. Run the web application by following the steps described in To Run the hello2_basicauth Example.

Specifying Security for Basic Authentication Using Annotations

The default authentication mechanism used by the GlassFish Server is basic authentication. With basic authentication, the GlassFish Server spawns a standard login dialog to collect user name and password data for a protected resource. Once the user is authenticated, access to the protected resource is permitted.

To specify security for a servlet, use the @ServletSecurity annotation. This annotation allows you to specify both specific constraints on HTTP methods and more general constraints that apply to all HTTP methods for which no specific constraint is specified. Within the @ServletSecurity annotation, you can specify the following annotations:

  • The @HttpMethodConstraint annotation, which applies to a specific HTTP method

  • The more general @HttpConstraint annotation, which applies to all HTTP methods for which there is no corresponding @HttpMethodConstraint annotation

Both the @HttpMethodConstraint and @HttpConstraint annotations within the @ServletSecurity annotation can specify the following:

  • A transportGuarantee element that specifies the data protection requirements (that is, whether or not SSL/TLS is required) that must be satisfied by the connections on which requests arrive. Valid values for this element are NONE and CONFIDENTIAL.

  • A rolesAllowed element that specifies the names of the authorized roles.

For the hello2_basicauth application, the GreetingServlet has the following annotations:

@WebServlet(name = "GreetingServlet", urlPatterns = {"/greeting"})
@ServletSecurity(
@HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL,
    rolesAllowed = {"TutorialUser"}))

These annotations specify that the request URI /greeting can be accessed only by users who have been authorized to access this URL because they have been verified to be in the role TutorialUser. The data will be sent over a protected transport in order to keep the user name and password data from being read in transit.

If you use the @ServletSecurity annotation, you do not need to specify security settings in the deployment descriptor. Use the deployment descriptor to specify settings for nondefault authentication mechanisms, for which you cannot use the @ServletSecurity annotation.

To Build, Package, and Deploy the hello2_basicauth Example Using NetBeans IDE

  1. Follow the steps in To Set Up Your System for Running the Security Examples.
  2. In NetBeans IDE, from the File menu, choose Open Project.
  3. In the Open Project dialog, navigate to:
    tut-install/examples/security/
  4. Select the hello2_basicauth folder.
  5. Select the Open as Main Project check box.
  6. Click Open Project.
  7. Right-click hello2_basicauth in the Projects pane and select Deploy.

    This option builds and deploys the example application to your GlassFish Server instance.

To Build, Package, and Deploy the hello2_basicauth Example Using Ant

  1. Follow the steps in To Set Up Your System for Running the Security Examples.
  2. In a terminal window, go to:
    tut-install/examples/security/hello2_basicauth/
  3. Type the following command:
    ant

    This command calls the default target, which builds and packages the application into a WAR file, hello2_basicauth.war, that is located in the dist directory.

  4. Make sure that the GlassFish Server is started.
  5. To deploy the application, type the following command:
    ant deploy

To Run the hello2_basicauth Example

  1. In a web browser, navigate to the following URL:
    https://localhost:8181/hello2_basicauth/greeting

    You may be prompted to accept the security certificate for the server. If so, accept the security certificate. If the browser warns that the certificate is invalid because it is self-signed, add a security exception for the application.

    An Authentication Required dialog box appears. Its appearance varies, depending on the browser you use.

  2. Type a user name and password combination that corresponds to a user who has already been created in the file realm of the GlassFish Server and has been assigned to the group of TutorialUser; then click OK.

    Basic authentication is case sensitive for both the user name and password, so type the user name and password exactly as defined for the GlassFish Server.

    The server returns the requested resource if all the following conditions are met.

    • A user with the user name you entered is defined for the GlassFish Server.

    • The user with the user name you entered has the password you entered.

    • The user name and password combination you entered is assigned to the group TutorialUser on the GlassFish Server.

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

  3. Type a name in the text field 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 the name you typed.

Next Steps

For repetitive testing of this example, you may need to close and reopen your browser. You should also run the ant undeploy and ant clean targets or the NetBeans IDE Clean and Build option to get a fresh start.

The hello1_formauth Example: Form-Based Authentication with a JavaServer Faces Application

This example explains how to use form-based authentication with a JavaServer Faces application. With form-based authentication, you can customize the login screen and error pages that are presented to the web client for authentication of the user name and password. When a user submits his or her name and password, the server determines whether the user name and password are those of an authorized user and, if authorized, sends the requested web resource.

This example, hello1_formauth, adds security to the basic JavaServer Faces application shown in Web Modules: The hello1 Example.

In general, the steps necessary for adding form-based authentication to an unsecured JavaServer Faces application are similar to those described in The hello2_basicauth Example: Basic Authentication with a Servlet. The major difference is that you must use a deployment descriptor to specify the use of form-based authentication, as described in Specifying Security for the Form-Based Authentication Example. In addition, you must create a login form page and a login error page, as described in Creating the Login Form and the Error Page.

The completed version of this example application can be found in the tut-install/examples/security/hello1_formauth/ directory.

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 a page to display if login authentication fails. This section discusses the login form and the error page used in this example. Specifying Security for the Form-Based Authentication Example shows how you specify these pages in the deployment descriptor.

The login page can be an HTML 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 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>

You can use Facelets tags instead of the HTML input tags, but you must use the HTML form tag, not a Facelets tag.

The full code for the login page used in this example can be found at tut-install/examples/security/hello1_formauth/web/login.xhtml. Here is the code for this page:

<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Login Form</title>
    </h:head>
    <h:body>
        <h2>Hello, please log in:</h2>
        <form method="post" action="j_security_check">
            <table columns="2" role="presentation"> 
                <tr>
                    <td><h:outputLabel for="j_username" 
                                       value="Please type your user name:"/></td>
                    <td><h:inputText id="j_username" autocomplete="off" 
                                     size="20" /></td>
                </tr>
                <tr>
                    <td><h:outputLabel for="j_password" 
                                       value="Please type your password:"/></td>
                    <td><h:inputSecret id="j_password" autocomplete="off" 
                                       size="20"/></td>
                </tr>
            </table>
            <p>
                <h:commandButton type="submit" value="Submit"/>
                &nbsp;
                <h:commandButton type="reset" value="Reset"/>
            </p>
        </form>
    </h:body>
</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/security/hello1_formauth/web/error.xhtml. 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 lang="en"
      xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Login Error</title>
    </head>
    <body>
    <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>.</p>
    <p><a href="faces/index.xhtml">Return to login page</a></p>

    </body>
</html>

Specifying Security for the Form-Based Authentication Example

This example takes a very simple servlet-based web application and adds form-based security. To specify form-based instead of basic authentication for a JavaServer Faces example, you must use the deployment descriptor.

The following sample code shows the security elements added to the deployment descriptor for this example, which can be found in tut-install/examples/security/hello1_formauth/web/WEB-INF/web.xml.

    <security-constraint>
        <display-name>Constraint1</display-name>
        <web-resource-collection>
            <web-resource-name>wrcoll</web-resource-name>
            <description/>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>TutorialUser</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>file</realm-name>
        <form-login-config>
            <form-login-page>/faces/login.xhtml</form-login-page>
            <form-error-page>/faces/error.xhtml</form-error-page>
        </form-login-config>
    </login-config>

    <security-role>
        <description/>
        <role-name>TutorialUser</role-name>
    </security-role>

To Build, Package, and Deploy the hello1_formauth Example Using NetBeans IDE

  1. Follow the steps in To Set Up Your System for Running the Security Examples.
  2. In NetBeans IDE, from the File menu, choose Open Project.
  3. In the Open Project dialog, navigate to:
    tut-install/examples/security/
  4. Select the hello1_formauth folder.
  5. Select the Open as Main Project check box.
  6. Click Open Project.
  7. Right-click hello1_formauth in the Projects pane and select Deploy.

To Build, Package, and Deploy the hello1_formauth Example Using Ant

  1. Follow the steps in To Set Up Your System for Running the Security Examples.
  2. In a terminal window, go to:
    tut-install/examples/security/hello1_formauth/
  3. Type 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/security/hello1_formauth/build/ directory, create the WAR file, and copy it to the tut-install/examples/security/hello1_formauth/dist/ directory.

  4. To deploy hello1_formauth.war to the GlassFish Server, type the following command:
    ant deploy

To Run the hello1_formauth Example

To run the web client for hello1_formauth, follow these steps.

  1. Open a web browser to the following URL:
    https://localhost:8181/hello1_formauth/

    The login form opens in the browser.

  2. Type a user name and password combination that corresponds to a user who has already been created in the file realm of the GlassFish Server and has been assigned to the group of TutorialUser.

    Form-based authentication is case sensitive for both the user name and password, so type the user name and password exactly as defined for the GlassFish Server.

  3. Click the Submit button.

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

    • A user with the user name My_Name is defined for the GlassFish Server.

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

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

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

      When these conditions are met and the server has authenticated the user, the application appears.

  4. Type 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.

Next Steps

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


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 Deploy if using NetBeans IDE.