The Java EE 6 Tutorial

Example: Securing an Enterprise Bean with Declarative Security

This section discusses how to configure an enterprise bean for basic user name/password authentication. When a bean that is constrained in this way is requested, the server requests a user name and password from the client and verifies that the user name and password are valid by comparing them against a database of authorized users on the GlassFish Server.

If the topic of authentication is new to you, see Specifying an Authentication Mechanism in the Deployment Descriptor.

This example demonstrates security by starting with the unsecured enterprise bean application, cart, which is found in the directory tut-install/examples/ejb/cart/ and is discussed in The cart Example.

    In general, the following steps are necessary to add user name/password authentication to an existing application that contains an enterprise bean. In the example application included with this tutorial, 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.

  1. Create an application like the one in The cart Example. The example in this tutorial starts with this example and demonstrates adding basic authentication of the client to this application. The example application discussed in this section can be found at tut-install/examples/security/cart-secure/.

  2. If you have not already done so, complete the steps in To Set Up Your System for Running the Security Examples to configure your system for running the tutorial applications.

  3. Modify the source code for the enterprise bean, CartBean.java, to specify which roles are authorized to access which protected methods. This step is discussed in Annotating the Bean.

  4. Build, package, and deploy the enterprise bean; then build and run the client application by following the steps in To Build, Package, Deploy, and Run the Secure Cart Example Using NetBeans IDE or To Build, Package, Deploy, and Run the Secure Cart Example Using Ant.

Annotating the Bean

The source code for the original cart application was modified as shown in the following code snippet (modifications in bold). The resulting file can be found in the following location:

tut-install/examples/security/cart-secure/cart-secure-ejb/src/java/cart/
ejb/CartBean.java

The code snippet is as follows:

package cart.ejb;

import cart.util.BookException;
import cart.util.IdVerifier;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;

@Stateful
@DeclareRoles("TutorialUser")
public class CartBean implements Cart {
    List<String> contents;
    String customerId;
    String customerName;

    public void initialize(String person) throws BookException {
        if (person == null) {
            throw new BookException("Null person not allowed.");
        } else {
            customerName = person;
        }

        customerId = "0";
        contents = new ArrayList<String>();
    }

    public void initialize(
        String person,
        String id) throws BookException {
        if (person == null) {
            throw new BookException("Null person not allowed.");
        } else {
            customerName = person;
        }

        IdVerifier idChecker = new IdVerifier();

        if (idChecker.validate(id)) {
            customerId = id;
        } else {
            throw new BookException("Invalid id: " + id);
        }

        contents = new ArrayList<String>();
    }

    @RolesAllowed("TutorialUser")
    public void addBook(String title) {
        contents.add(title);
    }

    @RolesAllowed("TutorialUser")
    public void removeBook(String title) throws BookException {
        boolean result = contents.remove(title);

        if (result == false) {
            throw new BookException("\"" + title + "\" not in cart.");
        }
    }

    @RolesAllowed("TutorialUser")
    public List<String> getContents() {
        return contents;
    }

    @Remove()
    @RolesAllowed("TutorialUser")
    public void remove() {
        contents = null;
    }
}

The @RolesAllowed annotation is specified on methods for which you want to restrict access. In this example, only users in the role of TutorialUser will be allowed to add and remove books from the cart and to list the contents of the cart. A @RolesAllowed annotation implicitly declares a role that will be referenced in the application; therefore, no @DeclareRoles annotation is required. The presence of the @RolesAllowed annotation also implicitly declares that authentication will be required for a user to access these methods. If no authentication method is specified in the deployment descriptor, the type of authentication will be user name/password authentication.

ProcedureTo Build, Package, Deploy, and Run the Secure Cart Example Using NetBeans IDE

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

  2. In NetBeans IDE, select File->Open Project.

  3. In the Open Project dialog, navigate to:


    tut-install/examples/security/
    
  4. Select the cart-secure folder.

  5. Select the Open as Main Project and Open Required Projects check boxes.

  6. Click Open Project.

  7. In the Projects tab, right-click the cart-secure project and select Build.

  8. In the Projects tab, right-click the cart-secure project and select Deploy.

    This step builds and packages the application into cart-secure.ear, located in the directory tut-install/examples/security/cart-secure/dist/, and deploys this EAR file to your GlassFish Server instance.

  9. To run the application client, right-click the cart-secure project and select Run.

    A Login for user: dialog box appears.

  10. In the dialog box, type the user name and password of a file realm user created on the GlassFish Server and assigned to the group TutorialUser; then click OK.

    If the user name and password you enter are authenticated, the output of the application client appears in the Output pane:


    ...
    Retrieving book title from cart: Infinite Jest
    Retrieving book title from cart: Bel Canto
    Retrieving book title from cart: Kafka on the Shore
    Removing "Gravity's Rainbow" from cart.
    Caught a BookException: "Gravity's Rainbow" not in cart.
    Java Result: 1
    ...

    If the user name and password are not authenticated, the dialog box reappears until you type correct values.

ProcedureTo Build, Package, Deploy, and Run the Secure Cart 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/cart-secure/
    
  3. To build the application and package it into an EAR file, type the following command at the terminal window or command prompt:


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


    ant deploy
    
  5. To run the application client, type the following command:


    ant run
    

    This task retrieves the application client JAR and runs the application client.

    A Login for user: dialog box appears.

  6. In the dialog box, type the user name and password of a file realm user created on the GlassFish Server and assigned to the group TutorialUser; then click OK.

    If the user name and password are authenticated, the client displays the following output:


    [echo] running application client container.
    [exec] Retrieving book title from cart: Infinite Jest
    [exec] Retrieving book title from cart: Bel Canto
    [exec] Retrieving book title from cart: Kafka on the Shore
    [exec] Removing "Gravity's Rainbow" from cart.
    [exec] Caught a BookException: "Gravity's Rainbow" not in cart.
    [exec] Result: 1

    If the username and password are not authenticated, the dialog box reappears until you type correct values.