The Java EE 5 Tutorial

Example: Securing an Enterprise Bean

This section discusses how to configure an enterprise bean for username-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 Application Server.

If the topic of authentication is new to you, please refer to the section titled Specifying an Authentication Mechanism.

For this tutorial, you will add the security elements to an enterprise bean; add security elements to the deployment descriptors; build, package, and deploy the application; and then build and run the client application.

The completed version of this example can be found at tut-install/javaeetutorial5/examples/ejb/cart-secure/. This example was developed by starting with the unsecured enterprise bean application, cart, which is found in the directory tut-install/javaeetutorial5/examples/ejb/cart/ and is discussed in The cart Example. You build on this example by adding the necessary elements to secure the application using username-password authentication.

    In general, the following steps are necessary to add username-password authentication to an enterprise bean. 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.

  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/javaeetutorial5/examples/ejb/cart-secure/.

  2. If you have not already done so, complete the steps in Building the Examples to configure your system properly for running the tutorial applications.

  3. If you have not already done so, add a user to the file realm and specify user for the group of this new user. Write down the user name and password so that you can use them for testing this application in a later step. Refer to the section Managing Users and Groups on the Application Server for instructions on completing this step.

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

  5. Modify the runtime deployment descriptor, sun-ejb-jar.xml, to map the role used in this application (CartUser) to a group defined on the Application Server (user) and to add security elements that specify that username-password authentication is to be performed. This step is discussed in Setting Runtime Properties.

  6. Build, package, and deploy the enterprise bean, then build and run the client application by following the steps in Building, Deploying, and Running the Secure Cart Example Using NetBeans IDE or Building, Deploying, and Running 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, method details removed to save space). The resulting file can be found in the following location:

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

The code snippet is as follows:

package com.sun.tutorial.javaee.ejb;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.annotation.security.RolesAllowed;
@Stateful()
public class CartBean implements Cart {

    String customerName;
    String customerId;
    List<String> contents;

    public void initialize(String person) throws BookException {
         ...
        }

    public void initialize(String person, String id) throws BookException {
         ... }

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

    @RolesAllowed("CartUser")
    public void removeBook(String title) throws BookException {
         ... }
    }
    @RolesAllowed("CartUser")
    public List<String> getContents() {
        return contents;
    }

    @Remove()
        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 CartUser will be allowed to add and remove books from the cart, and to list the contents of the cart. An @RolesAllowed annotation implicitly declares a role that will be referenced in the application; therefore, no @DeclareRoles annotation is required.

Setting Runtime Properties

The role of CartUser has been defined for this application, but there is no group of CartUser defined for the Application Server. To map the role that is defined for the application (CartUser) to a group that is defined on the Application Server (user), add a <security-role-mapping> element to the runtime deployment descriptor, sun-ejb-jar.xml, as shown below. In the original example, there was no need for this deployment descriptor, so it has been added for this example.

To enable username-password authentication for the application, add security elements to the runtime deployment descriptor, sun-ejb-jar.xml. The security element that needs to be added to the deployment descriptor is the <ior-security-config> element. The deployment descriptor is located in tut-install/javaeetutorial5/examples/ejb/cart-secure/cart-secure-ejb/src/conf/sun-ejb-jar.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-ejb-jar PUBLIC 
"-//Sun Microsystems, Inc.//DTD Application Server 9.0 EJB 3.0//EN" 
"http://www.sun.com/software/appserver/dtds/sun-ejb-jar_3_0-0.dtd">
<sun-ejb-jar>
    <security-role-mapping>
        <role-name>CartUser</role-name>
        <group-name>user</group-name>
    </security-role-mapping>
    <enterprise-beans>
        <unique-id>0</unique-id>
        <ejb>
            <ejb-name>CartBean</ejb-name>
            <jndi-name>jacc_mr_CartBean</jndi-name>
            <pass-by-reference>false</pass-by-reference>
            <ior-security-config>
                <transport-config>
                    <integrity>supported</integrity>
                    <confidentiality>supported</confidentiality>
                    <establish-trust-in-target>supported</establish-trust-in-target>
                    <establish-trust-in-client>supported</establish-trust-in-client>
                </transport-config>
                <as-context>
                    <auth-method>username_password</auth-method>
                    <realm>default</realm>
                    <required>true</required>
                </as-context>
                <sas-context>
                    <caller-propagation>supported</caller-propagation>
                </sas-context>
            </ior-security-config>
            <is-read-only-bean>false</is-read-only-bean>
            <refresh-period-in-seconds>-1</refresh-period-in-seconds>
            <gen-classes/>
        </ejb>
    </enterprise-beans>
</sun-ejb-jar>

For more information on this topic, read Specifying an Authentication Mechanism and Configuring IOR Security.

Building, Deploying, and Running the Secure Cart Example Using NetBeans IDE

    Follow these instructions to build, deploy, and run the cart-secure example in your Application Server instance using NetBeans IDE.

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

  2. In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/ejb/.

  3. Select the cart-secure folder.

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

  5. Click Open Project.

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

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

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

  8. To run secure cart’s application client, select Run->Run Main Project. You will be prompted for your username and password.

  9. Enter the username and password of a user that has been entered into the database of users for the file realm and has been assigned to the group of user.

If the username and password you enter are authorized, you will see the output of the application client 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
run-cart-secure-app-client:

Building, Deploying, and Running the Secure Cart Example Using Ant

    To build, deploy, and run the secure EJB example using the Ant tool, follow these steps:

  1. If you have not already done so, specify properties specific to your installation in the tut-install/javaeetutorial5/examples/bp-project/build.properties file and the tut-install/javaeetutorial5/examples/common/admin-password.txt file. See Building the Examples for information on which properties need to be set in which files.

  2. If you have not already done so, add a user to the file realm and specify user for the group of this new user. Refer to the section Managing Users and Groups on the Application Server for instructions on completing this step.

  3. From a terminal window or command prompt, go to the tut-install/javaeetutorial5/examples/ejb/cart-secure/ directory.

  4. Build, package, and deploy the enterprise application, and build and run the client, by entering the following at the terminal window or command prompt in the ejb/cart-secure/ directory:


    ant all
    

    Note –

    This step assumes that you have the executable for ant in your path; if not, you will need to provide the fully qualified path to the ant executable. This command runs the ant target named all in the build.xml file.


  5. A Login for User dialog displays. Enter a user name and password that correspond to a user set up on the Application Server with a group of user. Click OK.

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


run:
    [echo] Running appclient for Cart.

appclient-command-common:
    [exec] Infinite Jest
    [exec] Bel Canto
    [exec] Kafka on the Shore
    [exec] Caught a BookException: "Gravity’s Rainbow" not in cart.

If the username and password are not authenticated, the client displays the following error:


run:
    [echo] Running appclient for Cart.

appclient-command-common:
    [exec] Caught an unexpected exception!
    [exec] javax.ejb.EJBException: nested exception is: java.rmi.AccessException:
     CORBA NO_PERMISSION 9998 Maybe; nested exception is:
    [exec]     org.omg.CORBA.NO_PERMISSION:
     ----------BEGIN server-side stack trace----------
    [exec] org.omg.CORBA.NO_PERMISSION:   vmcid: 0x2000  minor code: 1806

If you see this response, verify the user name and password of the user that you entered in the login dialog, make sure that user is assigned to the group user, and rerun the client application.